使用“#"运算符来计算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
的序列.
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屋!
查看全文