Why length is different in Lua

不想你离开。 提交于 2019-12-31 01:55:32

问题


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

why the second one is not 6 too??


回答1:


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.

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

See Lua 5.2 Reference Manual: The length operator.



来源:https://stackoverflow.com/questions/22059329/why-length-is-different-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!