counting string-indexed tables in lua

我与影子孤独终老i 提交于 2021-01-27 14:08:04

问题


I am trying to count elements in a table that has some elements indexed with strings. When I try to use the # operator, it just ignores string indexed ones. example:

local myTab = {1,2,3}
print(#myTab)

will return 3

local myTab = {}
myTab["hello"] = 100
print(#myTab)

will return 0 mixing them, I tried

local myTab = {1,2,3,nil,5,nil,7}
print(#myTab)
myTab["test"] = try
print(#myTab)

returned 7 and then 3, that is right because I read somewhere that the # operator stops when it finds a nil value (but then why the first print printed 7?)

last, I tried

local myT = {123,456,789}
myT["test"] = 10
print(#myT)

printing 3, not 4

Why?


回答1:


The rule is simple, from the length operator:

Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n. In that case, n is its length.

In your example:

local myTab = {1,2,3,nil,5,nil,7}

#mytab is undefined because myTab isn't a sequence, with or without myTab["test"] = try.

local myT = {123,456,789}

myT is a sequence, and the length is 3, with or without myT["test"] = 10



来源:https://stackoverflow.com/questions/27983125/counting-string-indexed-tables-in-lua

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