簡體   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