您正在经历的是参数修剪。
让我们来看看你有什么,并解释当 Lua 解析它时发生了什么。
-- T is equal to 1, 2, 3, (NOTHING)
-- Therefore we should trim the nil from the end.
t = {1, 2, 3, nil};
-- T is equal to 1, nil, 3, 4
-- We have something on the end after nil, so we'll count nil as an element.
t = {1, nil, 3, 4};
同样的情况也发生在函数中。这可能有点麻烦,但有时很方便。举个例子:
-- We declare a function with x and y as it's parameters.
-- It expects x and y.
function Vector(x, y) print(x, y); end
-- But... If we add something unexpected:
Vector("x", "y", "Variable");
-- We'll encounter some unexpected behaviour. We have no use for the "Variable" we handed it.
-- So we just wont use it.
反之亦然。如果你提交一个需要 X、Y 和 Z 的函数,但你提交的是 X 和 Y,你将传递 nil 而不是 Z。
请参阅this answer here,因为您确实可以使用以下方法在表中表示 nil:
-- string int nil
t = {"var", "1", "nil"};