为什么 Lua 中的长度不同 [英] Why length is different in Lua

查看:11
本文介绍了为什么 Lua 中的长度不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 corona sdk 学习 Lua,我有这些

I'm learning Lua for corona sdk and I have these

local type1 = {nil, "(", nil, "x" ,nil , ")" ; n=6}
local type2 = {"(",nil, "x",nil, ")",nil ; n=6}
print(#type1)   --prints 6
print(#type2)   --prints 3

为什么第二个也不是6??

why the second one is not 6 too??

推荐答案

# 运算符不适用于每个表,它只适用于一个序列,即其正数的集合对于某些整数 n,数字键等于 {1..n}.在这种情况下, n 是它的长度.例如,local t = {"hello", 42, true} 是一个序列.

The # operator doesn't work on every table, it works only on a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some integer n. In that case, n is its length. For instance, local t = {"hello", 42, true} is a sequence.

但是您的两个表都没有顺序,因为它们有 nil 的漏洞".

But both your tables are not sequence because they have "holes" of nil.

请参阅Lua 5.2 参考手册:长度运算符.

这篇关于为什么 Lua 中的长度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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