lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hans van der Meer wrote:
Trying to find in C program the length of a table with lua_objlen that returned zero, though there are entries in the table (I made them myself). Testing in the lua interpreter gives the following results I cannot explain:

Lua 5.1.3  Copyright (C) 1994-2008, PUC-Rio
> local io = require "io" print(io, #io)
table: 0x102080    0
> local ta= {"a","b","c"} print(ta, #ta)
table: 0x107af0    3
This is correct according to the reference manual:

The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n may be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t may be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

The io table has no entries with integer indices. There are a number of ways that you can get the total number of entries in a table. Following is one, I'm sure others will post better techniques:

-- tab is the name of the table whose size you want
function tabLen(tab)
   local count = 0
   table.foreach(tab, function(k,v) count = count+1 end)
   return count

-- Matt