1

I am basically doing some testing to get to know the Lua language a bit better. I found a bug that makes zero sense to me.

Function:

local function d(c)
    return (!c and print("c", false) or print("c", true))
end

local function a(b, c)
    return (!b and d(c) or print("b", true))
end

When i run a(1, nil) or a(1, 1) it outputs b true, but if i run a(nil, 1) then it outputs c true and b true

If anyone could enlighten me on why it returns two value when that technically shouldn't be possible?

2
  • 1
    You are confusing return values with printed output. On top of that you can return multiple values in Lua. Commented Nov 9, 2018 at 22:03
  • I know that it is possible to return multiple values in lua, but for this case it should choose either, not both. But thanks for explaining why i experienced this bug. Commented Nov 9, 2018 at 23:07

1 Answer 1

2

Maybe you already understand what's happening, but I've already written this post. Lua doesn't have a ! operator; I guess you meant not. (I wouldn't be surprised if someone has made a patched version of Lua with ! in place of not.)

a(nil, 1) returns not nil and d(1) or print("b", true). Now, not nil evaluates to true and d(1) evaluates to nil, so we have true and nil or print("b", true), which in turn evaluates to nil or print("b", true), and therefore print("b", true) is evaluated.

As to why d(1) evaluates to nil: it returns not 1 and print("c", false) or print("c", true). That is equivalent to not 1 and nil or nil because print always returns nothing when it is called, and nothing is treated as nil by the operators and and or. not x and nil or nil always evaluates to nil whether x is truthy or falsy, so d always returns nil. (The only difference is that if d receives a falsy value, both print calls are evaluated.)

You can verify that print returns nothing by calling type(print('a')): it throws the error "bad argument #1 to 'type' (value expected)", whereas type(nil) returns "nil".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.