使用“#"运算符来计算Lua中表格的长度? [英] use "#" operator to calculate the length of a table in Lua?

查看:108
本文介绍了使用“#"运算符来计算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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆