'nil' 作为 Lua 表中的元素?

Zac*_*Lee 5 lua lua-table

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

我不明白的是

下面的代码打印3

t = {1, 2, 3, nil};
print(#t);
Run Code Online (Sandbox Code Playgroud)

但下面的打印4

t = {1, nil, 3, 4};
print(#t);
Run Code Online (Sandbox Code Playgroud)

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

小智 4

你所经历的是争论修剪。

让我们看一下您所拥有的内容并解释当 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};
Run Code Online (Sandbox Code Playgroud)

同样的情况也发生在函数中。这可能有点麻烦,但有时很方便。以下面为例:

-- 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.
Run Code Online (Sandbox Code Playgroud)

反之亦然。如果你传递一个需要 X、Y 和 Z 的函数,但你传递的是 X 和 Y,那么你将传递 nil 而不是 Z。

请参阅此处的答案,因为您确实可以使用以下内容在表中表示 nil:

--  string  int   nil
t = {"var", "1", "nil"};
Run Code Online (Sandbox Code Playgroud)