Search code examples
lua

Evaluating a function that returns nothing


function foo() end

if foo() then end

I saw some code that did this and wondered: What is being evaluated by the if statement when foo() does not return anything.

Tried it in an interpreter and it evaluates to false, but is that a guarantee? Is it evaluating the last thing returned somewhere else?


Solution

  • If control reaches the end of a function without encountering a return statement, the function implicitly returns nothing. As the syntax for if requires a single expression, the zero-length multires expression of nothing is adjusted to a single nil value.

    In a control structure (if, while, repeat), a condition expression equal to nil tests false (conversely, not nil is true).

    See Lua 5.4: