I need impelement a C function for lua script to call.I shall return an array as table from that function.I used the code blow but crashed.Could anyone tell me how to use it?
struct Point {
int x, y;
}
typedef Point Point;
static int returnImageProxy(lua_State *L)
{
Point points[3] = {{11, 12}, {21, 22}, {31, 32}};
lua_newtable(L);
for (int i = 0; i 3; i++) {
lua_newtable(L);
lua_pushnumber(L, points[i].x);
lua_rawseti(L, -2, 2*i+1);
lua_pushnumber(L, points[i].y);
lua_rawseti(L, -2, 2*i+2);
lua_settable(L,-3);
}
return 1; // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
}
In Lua, the table library provides functions to insert elements into the table. The insert function usually takes two arguments, the first argument is usually the name of the table from which we want to insert the element to, and the second argument is the element that we want to insert.
In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.
The table type implements associative arrays. An associative array is an array that can be indexed not only with numbers, but also with strings or any other value of the language, except nil. Moreover, tables have no fixed size; you can add as many elements as you want to a table dynamically.
Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way. When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack.
Need to change the lua_settable
as @lhf mentions. Also, you are always adding into the first 2 indices of the sub-tables
typedef struct Point {
int x, y;
} Point;
static int returnImageProxy(lua_State *L)
{
Point points[3] = {{11, 12}, {21, 22}, {31, 32}};
lua_newtable(L);
for (int i = 0; i < 3; i++) {
lua_newtable(L);
lua_pushnumber(L, points[i].x);
lua_rawseti(L, -2, 1);
lua_pushnumber(L, points[i].y);
lua_rawseti(L, -2, 2);
lua_rawseti(L, -2, i+1);
}
return 1; // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
}
Try replacing lua_settable(L,-3)
with lua_rawseti(L,-2,i+1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With