Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table.getn() returns 0?

Tags:

c

lua

I've embedded Lua into my C application, and am trying to figure out why a table created in my C code via:

lua_createtable(L, 0, numObjects);

and returned to Lua, will produce a result of zero when I call the following:

print("Num entries", table.getn(data))

(Where "data" is the table created by lua_createtable above)

There's clearly data in the table, as I can walk over each entry (string : userdata) pair via:

for key, val in pairs(data) do
  ...
end

But why does table.getn(data) return zero? Do I need to insert something into the meta of the table when I create it with lua_createtable? I've been looking at examples of lua_createtable use, and I haven't seen this done anywhere....

like image 898
jimt Avatar asked Mar 08 '12 05:03

jimt


2 Answers

table.getn (which you shouldn't be using in Lua 5.1+. Use the length operator #) returns the number of elements in the array part of the table.

The array part is every key that starts with the number 1 and increases up until the first value that is nil (not present). If all of your keys are strings, then the size of the array part of your table is 0.

like image 150
Nicol Bolas Avatar answered Oct 11 '22 06:10

Nicol Bolas


Although it's a costly (O(n) vs O(1) for simple lists), you can also add a method to count the elements of your map :

>> function table.map_length(t)
    local c = 0
    for k,v in pairs(t) do
         c = c+1
    end
    return c
end

>> a = {spam="data1",egg='data2'}
>> table.map_length(a)
2

If you have such requirements, and if your environment allows you to do so think about using penlight that provides that kind of features and much more.

like image 29
Jocelyn delalande Avatar answered Oct 11 '22 07:10

Jocelyn delalande