use “#” operator to calculate the length of a table in Lua? [duplicate]

北战南征 提交于 2019-12-02 04:23:30

问题


I have a question when I use # to calculte the length of a table. For Example:

local t = {"a", "b"}
local t1 = {"a", nil}
print(#t)       -- 2
print(#t1)      -- 1

local t = {"a", "b"}
local t1 = {nil, "a"}
print(#t)       -- 2
print(#t1)      -- 2

can someone tell me why it is?


回答1:


Unless __len metamethod is defined, # operator can only be operated on a table that is a sequence.

A sequence is, a table that, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n.

In your example:


local t = {"a", "b"}

t is a sequence that has a length of 2.


local t1 = {"a", nil}

is equivalent to local t1 = {"a"}, so t1 is a sequence that has a length of 1.


local t1 = {nil, "a"}

t1 is not a sequence, so #t1 is not defined.



来源:https://stackoverflow.com/questions/29248727/use-operator-to-calculate-the-length-of-a-table-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!