相关疑难解决方法(0)

为什么Lua的长度(#)运算符返回意外值?

Lua有#运算符来计算用作数组的表的"长度".我检查了这个操作员,我感到很惊讶.

这是代码,我让它在Lua 5.2.3下运行:

t = {};
t[0] = 1;
t[1] = 2;
print(#t); -- 1 aha lua counts from one
t[2] = 3;
print(#t); -- 2 tree values, but only two are count
t[4] = 3;
print(#t); -- 4  but 3 is mssing?
t[400] = 400;
t[401] = 401;
print(#t); -- still 4, now I am confused?


t2 = {10, 20, nil, 40}
print(#t2); -- 4 but documentations says this is not a sequence?
Run Code Online (Sandbox Code Playgroud)

有人可以解释规则吗?

lua

18
推荐指数
1
解决办法
6662
查看次数

标签 统计

lua ×1