lua-users home
lua-l archive

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


2007/5/27, Duncan Cross <duncan.cross@gmail.com>:
I'd like to make use of table.sort inside a C module in order to sort
a (hidden, behind-the-scenes) table. The three options that I can see
are:

1) Do table lookups to get at it from the globals table after the
library has been opened
2) Modify the table library to make the function nonstatic and use it that way
3) Copy only the function I want out into accessible code

None of which particularly appeal to me. Is there a better way I'm
missing that other people would use in this situation?

Some C functions of the Lua standard lib rely on being closures, with
an environment and/or upvalues. You can't expose and call these
functions directly. So unless you are sure that table.sort is not one
of these functions, your first solution is the only way to go.
Something like that:

void sorttable(lua_State* L, int index)
{
   luaL_checktype(L, 1, LUA_TTABLE);
   lua_getfield(L, LUA_GLOBALSINDEX, "table");
   lua_getfield(L, -1, "sort");
   lua_remove(L, -2); /* remove 'table' from stack */
   lua_pushvalue(L, index);
   lua_call(L, 1, 0);
}

You can save one of the two table lookups by storing a reference to
table.sort somewhere accessible by your code (for example the
registry, or a function environment).