问题
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 tablet
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 integern
. 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