Lua 参数未正确扩展
Lua parameters not expanding properly
我是 Lua 的新手,也许这是一个菜鸟问题,但为什么下面的代码会失败?据我了解 foo returns 两个参数,因为在 Lua 中你可以传递任意数量的参数,第一次传递很好,但第二次调用失败了断言。
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
请阅读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
是解析为 true, true
的表达式列表,因为 foo()
既不是该列表的唯一表达式,也不是最后一个表达式。
而 true, foo()
将解析为 true, true, {}
我是 Lua 的新手,也许这是一个菜鸟问题,但为什么下面的代码会失败?据我了解 foo returns 两个参数,因为在 Lua 中你可以传递任意数量的参数,第一次传递很好,但第二次调用失败了断言。
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
请阅读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
是解析为 true, true
的表达式列表,因为 foo()
既不是该列表的唯一表达式,也不是最后一个表达式。
而 true, foo()
将解析为 true, true, {}