Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting string-indexed tables in lua

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?

like image 528
Federico Fallico Avatar asked May 30 '26 08:05

Federico Fallico


1 Answers

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

like image 59
Yu Hao Avatar answered Jun 01 '26 03:06

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!