Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return several parameter from lua C function

Tags:

c

lua

I want to get several parameters in Lua from a C function. I tried to push several arguments on the lua stack:

static int myFunc(lua_State *state)
{
    lua_pushnumber(state, 1);
    lua_pushnumber(state, 2);
    lua_pushnumber(state, 3);

    return 1;
}

and call it in Lua like this:

local a,b,c = myFunc()

Unfortunately b and c values are nil. I dont want to write a function for every value I need but to take advantage of Luas capabilities to retrieve several arguments from a function.

like image 594
Objective Avatar asked Oct 24 '25 03:10

Objective


1 Answers

The return value of the C function is the number of values returned.

Change it to return 3; and you're good to go.

Here, have a reference from Programming in Lua:

static int l_sin (lua_State *L) {
  double d = lua_tonumber(L, 1);  /* get argument */
  lua_pushnumber(L, sin(d));  /* push result */
  return 1;  /* number of results */
}
like image 54
Bartek Banachewicz Avatar answered Oct 26 '25 18:10

Bartek Banachewicz