8

Here is a code:

users = {}  
users["aaa"] = "bbbb";
users["bbb"] = "bbbb";
users["ccc"] = "bbbb";
print("Users count ", table.getn(users));

Why table.getn(users) always returns 0? BTW, #users returns 0 too. So, am I doing something wrong and there is another way to get the amount of elements in the array?

Tutankhamen
  • 3,532
  • 1
  • 30
  • 38
  • no, it always returns 0 whatever I write. It looks like these methods doesn't work with hash/string key index type of array... – Tutankhamen Feb 19 '13 at 23:59
  • Exactly. That's what the answers on that page tell you. It's your exact question: a table that's not empty, but has no array elements. – Nicol Bolas Feb 20 '13 at 00:16

1 Answers1

16

table.maxn and # look for numeric indices; they won't see your string indices.

As for getting the number of elements in an array with arbitrary indices, I'd probably walk the array using something like:

Count = 0
for Index, Value in pairs( Victim ) do
  Count = Count + 1
end

but I'm an idiot.

Anachronda
  • 184
  • 1
  • 2
  • Thanks, I know that, but I need O(1), not O(n) method. I think there should be something like that. Am I wrong? – Tutankhamen Feb 19 '13 at 23:57
  • 1
    @Tutankhamen: Thinking that such a thing would exist will not make it so. Besides, why does it matter? You can't access those fields by numeric index, so why do you need to know how many there are? – Nicol Bolas Feb 20 '13 at 00:17
  • for example - i can have up to 30 users per session, so, I want to know how much are already there, etc. – Tutankhamen Feb 20 '13 at 00:23
  • 2
    BTW, if there is no other way then I will accept this answer... But anyway I think it is abnormal that array doesn't provide such interface. – Tutankhamen Feb 20 '13 at 00:29
  • Well, if you read the manual closely, it states that table.maxn and # walk the table, so they wouldn't be O(1) anyway. – Anachronda Feb 20 '13 at 00:47
  • 1
    Gah! Didn't realize "enter" would post the comment. You could do a metatable with custom __index and __newindex functions to count entries as they are added or removed, but I haven't given it any thought. – Anachronda Feb 20 '13 at 00:49
  • Thanks, I will try to implement it using metatable. – Tutankhamen Feb 20 '13 at 01:04