[英]How to return an array as table from C function to lua?
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? 我需要一个C函数来为lua脚本调用。我将从该函数返回一个数组作为表。我使用代码打击但崩溃了。有人能告诉我如何使用它吗?
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}}
}
Need to change the lua_settable
as @lhf mentions. 需要将
lua_settable
更改为@lhf提及。 Also, you are always adding into the first 2 indices of the sub-tables 此外,您总是添加到子表的前2个索引中
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}}
}
尝试用lua_settable(L,-3)
lua_rawseti(L,-2,i+1)
替换lua_settable(L,-3)
lua_rawseti(L,-2,i+1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.