0

How do I create a 1d numeric table from a C callback that may be called many times? The library provides the following callback function signature:

int callback(int x, int y, int z, void *cb);

Suppose it is called three times with the following values:

(1) x=3 y=1 z=4 cb=<ptr>
(2) x=1 y=5 z=9 cb=<ptr>
(3) x=2 y=6 z=5 cb=<ptr>

I expect the resulting lua table to look like this:

{ [1]=3, [2]=1, [3]=4, [4]=1, [5]=5, [6]=9, [7]=2, [8]=6, [9]=5 }

Here is the relevant code:

int callback(int x, int y, int z, void *cb) {
  (lua_State *)L = cb;
  // what do I add here? something with lua_pushnumber()?
}

static int caller(lua_state *L) {
  lua_createtable(L); //empty table is now on top of stack
  exec(callback, L); //can be called any amount of times
  return 1;
}

As the callback may be called 1000s of times, I'd like x, y, and z to be added immediately to the table to not consume the entire lua stack if possible.

ruser9575ba6f
  • 258
  • 1
  • 10

1 Answers1

0

A possible solution would be

int index = 1;

int callback(int x, int y, int z, void *cb) {
  (lua_State *)L = cb;
  lua_pushinteger(L, index++);
  lua_pushinteger(L, x);
  lua_settable(L, -3);

  lua_pushinteger(L, index++);
  lua_pushinteger(L, y);
  lua_settable(L, -3);

  lua_pushinteger(L, index++);
  lua_pushinteger(L, z);
  lua_settable(L, -3);

}

static int caller(lua_state *L) {
  lua_createtable(L); //empty table is now on top of stack
  exec(callback, L); //can be called any amount of times
  return 1;
}
Marc Balmer
  • 1,780
  • 1
  • 11
  • 18