c - 如何将数组作为表从 C 函数返回到 lua?

标签 c lua

我需要为 lua 脚本调用一个 C 函数。我将从该函数返回一个数组作为表。我使用了代码 blow 但崩溃了。谁能告诉我如何使用它?


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}}
}

最佳答案

如@lhf 所述,需要更改 lua_settable。此外,您总是添加到子表的前 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}}
}

关于c - 如何将数组作为表从 C 函数返回到 lua?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18486712/

相关文章:

lua - 使用 Lua 模式匹配的可选组捕获

lua - 在两个表中调用函数给出相同的输出

c - n - 1 位数字

c - memcpy 什么都不做

c - printf 期间出现访问冲突错误

lua - 在 Torch 中可视化神经网络层,无需 itorch

lua - 当值为 false 时立即停止 while 循环

c - 我如何在 C 中阅读这个复杂的声明?

c - 在后台执行命令

python - Lua 的科学库?