Ran into this problem earlier. For a multi return value function
fn=function() return 'a','b' end
the call
print(fn())
returns a b
but the call
print(fn() or nil)
returns only a
why? or
should not matter since the first call was successful right?
Function return values In most languages, functions always return one value. To use this, put comma-separated values after the return keyword: > f = function () >> return "x", "y", "z" -- return 3 values >> end > a, b, c, d = f() -- assign the 3 values to 4 variables.
In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f .
A comment starts with a double hyphen ( -- ) anywhere outside a string. They run until the end of the line. You can comment out a full block of code by surrounding it with --[[ and --]] . To uncomment the same block, simply add another hyphen to the first enclosure, as in ---[[ .
The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .
Quoting from Programming in Lua §5.1 – Multiple Results
Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all results from the function. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.
In the case of your example, the return value of fn()
is used as an expression (the left operand of or
operator), so only the first value is kept.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With