jimt
jimt

Reputation: 2010

Lua table.getn() returns 0?

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....

Upvotes: 10

Views: 16770

Answers (4)

Max
Max

Reputation: 11

for k,v in pairs(tbl) do count = count + 1 end

Upvotes: 0

Jocelyn delalande
Jocelyn delalande

Reputation: 5394

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.

Upvotes: 3

Nicol Bolas
Nicol Bolas

Reputation: 474316

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.

Upvotes: 25

daurnimator
daurnimator

Reputation: 4311

the # operator (and table.getn) effectivly return the size of the array section (though when you have a holey table the semantics are more complex)

It does not count anything in the hash part of the table (eg, string keys)

Upvotes: 3

Related Questions