繁体   English   中英

如何将表(数字列表)从Lua传递给C并访问它

[英]How to pass Table(list of numbers) from Lua to C and access it

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

假设我有以下表格:

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

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

我发送它使用:

quicksort(x)

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

如何在C中访问x

传递给函数的表将位于函数的堆栈中。 您可以使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM