lua-users home
lua-l archive

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


On Sunday 09 February 2003 01:40, you wrote:
> Would someone please post a quick example of how to use
> 'lua_call' to call 'table.getn()' on a table that's being
> passed from a script?
>
> I'm trying to update a lua-4.0 extension module to lua-5.0-beta
> that checked using this sort of approach:
>
>    luaL_check_type(L, index, LUA_TTABLE);  /* is it a table? */
>    n = lua_getn(L, index);
>    if( n != some_number ) { blah... }
>
> Thanks,
> Dean.

Hi Dean,

getn is no longer in the core.  It has been moved to src/lib/ltablib.c.
You can either make sure you set the table's size "n", or else you can call 
tabe.getn.

  luaL_checktype(L, index, LUA_TTABLE);  /* is it a table? */
  lua_pushliteral(L, "n");
  lua_gettable(L, index);
  n = lua_tonumber(L, -1);

Here is how to call table.getn

static int my_getn(lua_State *L, int index)
{
  int n;
  luaL_checktype(L, index, LUA_TTABLE);  /* is it a table? */
  lua_pushliteral(L, "table");
  lua_gettable(L, LUA_GLOBALSINDEX);
  lua_pushliteral(L, "getn");
  lua_gettable(L, -2);
  lua_pushvalue(L, index);
  lua_call(L, 1, 1);  /* call table.getn(t) */
  n = lua_tonumber(L, -1);
  lua_pop(L, 2);
  return n;
}

- Peter Shook