sean riley sean riley - 2 months ago 13
C Question

How to do lua table operations from C?

I need to perform operations on Lua tables from C where the tables are treated as lists or queues. Specifically I need to insert an element at the head, and remove the head element, and have the other elements move to accommodate the new element.

This would be simple in straight lua, I'd use

table.insert
and
table.remove
. But in C?

There are functions in the Lua C api such as lua_settable, but no equivalents for
table.insert
and table.remove that are surfaced. It looks like there are internal C functions inside the interpreter called
tinsert
and
tremove
, but they are not part of the api.

Do I really have to call out to a lua function that does it for me?

Answer

I believe you can reuse the functions

static int tinsert (lua_State *L)
static int tremove (lua_State *L)

and the macro

#define aux_getn(L,n)   (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n))

which are in the ltablib.c. They depend only on Lua's API.

Comments