Reputation: 483
I am pretty new to Lua and maybe this is a noobie question but why is the below code failing? As far as I understand foo returns two parameters and since in Lua you can pass as many parameters as your heart desires the first passes just fine but the second call fails the assert.
function foo()
return true, {}
end
function bar(a,b,c)
assert(type(b)=="table", "Expected table as the second parameter")
print("Fine")
end
bar(foo()) -- Fine
bar(foo(),true) -- Expected table as the second parameter
https://www.lua.org/cgi-bin/demo
Upvotes: 3
Views: 79
Reputation: 28950
Please read Lua 3.5 Reference Manual: 3.4 Expressions
Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see §3.3.6), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values.
foo(),true
is a list of expressions that resolves to true, true
as foo()
is neither the only nor the last expression of that list.
Whereas true, foo()
would resolve to true, true, {}
Upvotes: 3