See screencap:
If you can't see the screencap, it was me typing this in:
>T={}
>T["ZOT"]=123
>T["ZAP"]=456
>PRINT(#T)
0
>
|
Does the table # operator not work the way I think it does? Or is adding elements to the table not incrementing the size the way it should?
Lua tables have two parts, a sequential part, and a key/value part.
If you insert into indexes 1, 2, 3, 4, then the length will be 4. The '#' operator starts at index 1 and counts up until there is a hole.
More examples:
For indexes 2, 3, 4, 5, the length would be 0 since 1 is not set.
For indexes 1, 2, 3, 5, the length would be 3 since 4 is not set.
I'm not particularly a fan of that myself, but it does have some nice benefits of keeping the table type simple.
If you want to count the number of items in a table without sequential indexes, you have to count them using pairs, foreach, or something similar.
slembcke is right, but if you want "#" to return the length of your kind of table correctly, you can change the behavior of __len with setmetatable(). Here's an example :
t={}
t["zot"] = 123
t["zap"] = 456
mt = {}
mt.__len = function(s)
l = 0
for k,v in pairs(s)do
l += 1
end
return l
end
setmetatable(t,mt)
print(#t)
|
This should return 2
Got it. I had a feeling something so frequently used wasn't likely to be broken.
Thanks for the clarification, and also the hint about metatables. I don't think I'd want to do that in this case, but I do keep forgetting you can override stuff with them. I forget things a lot. :)
I'll mark this as resolved.
[Please log in to post a comment]



