Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of an array in LUA? [duplicate]

Tags:

lua

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?

like image 909
Tutankhamen Avatar asked Feb 19 '13 23:02

Tutankhamen


People also ask

How do I get the size of an array in Lua?

The setn function is used to set the size of the array explicitly and the getn is used to extract the size that was set by the setn.

Does Lua have array?

In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

How big can a Lua table be?

Because 64 Bit per number * 2^25 = 2147483648 Bits which are exactly 2 GB.


1 Answers

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.

like image 85
Anachronda Avatar answered Oct 23 '22 19:10

Anachronda