使用“#"运算符来计算Lua中表的长度? [英] use "#" operator to calculate the length of a table in Lua?
本文介绍了使用“#"运算符来计算Lua中表的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 #
来计算表格的长度时,我有一个问题.例如:
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?
推荐答案
除非定义了 __len
元方法,#
操作符只能对一个是序列的表进行操作.
Unless __len
metamethod is defined, #
operator can only be operated on a table that is a sequence.
一个序列是一个表,对于某个非负整数n
,它的正数字键的集合等于{1..n}
.
A sequence is, a table that, the set of its positive numeric keys is equal to {1..n}
for some non-negative integer n
.
在你的例子中:
local t = {"a", "b"}
t
是一个长度为 2
的序列.
t
is a sequence that has a length of 2
.
local t1 = {"a", nil}
等价于local t1 = {"a"}
,所以t1
是一个长度为1
的序列.><小时>
is equivalent to local t1 = {"a"}
, so t1
is a sequence that has a length of 1
.
local t1 = {nil, "a"}
t1
不是序列,所以 #t1
没有定义.
t1
is not a sequence, so #t1
is not defined.
这篇关于使用“#"运算符来计算Lua中表的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文