我想知道 nil 是否是 Lua 表中的有效元素。

我不明白的是

以下代码打印 3

t = {1, 2, 3, nil};
print(#t);

但以下打印 4
t = {1, nil, 3, 4};
print(#t);

我不明白为什么这两个代码输出不同的结果。

最佳答案

您正在经历的是参数修剪。

让我们来看看你所拥有的,并解释 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"};

关于lua - 'nil' 作为 Lua 表中的一个元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51852969/

10-11 22:31
查看更多