如何将Lua中的Table(数字列表)传递到C中并访问它

我想将一个包含数字的 Lua 列表传递给 C 并在 C 中访问它。我该怎么做?

假设我有以下表格:

x = {1, 2, 3, 9, 5, 6}

我想将其发送到 C 并在 C 中将此表格存储在数组中。

我使用以下方式发送:

quicksort(x)

其中 quicksort 是我在 C 中定义的函数。

如何在 C 中访问 x

原文链接 https://stackoverflow.com/questions/8122709

点赞
stackoverflow用户513763
stackoverflow用户513763

你传递给函数的表将在函数的栈上。您可以使用 lua_getfieldlua_gettable 索引它。

使用 lua_next 遍历表,如果需要,可以在 C 中填充数组; 尽管如此,对于数组,简单地从 1 迭代到 #t 就足够了。

一些示例实用程序代码(未经测试):

int* checkarray_double(lua_State *L, int narg, int *len_out) {
    luaL_checktype(L, narg, LUA_TTABLE);

    int len = lua_objlen(L, narg);
    *len_out = len;
    double *buff = (double*)malloc(len*sizeof(double));

    for(int i = 0; i < len; i++) {
        lua_pushinteger(L, i+1);
        lua_gettable(L, -2);
        if(lua_isnumber(L, -1)) {
            buff[i] = lua_tonumber(L, -1);
        } else {
            lua_pushfstring(L,
                strcat(
                    strcat(
                        "invalid entry #%d in array argument #%d (expected number, got ",
                        luaL_typename(L, -1)
                    ),
                    ")"
                ),
                i, narg
            );
            lua_error(L);
        }
        lua_pop(L, 1);
    }

    return buff;
}
2011-11-14 14:29:43