2

我正在尝试使用 c API 和 Lua5.1 调用表。

我正在按照以下步骤进行操作:

  1. 创建一个具有__call元功能的表“mt”
  2. 创建一个表“newT”并将“mt”设置为“newT”元表
  3. pcall“新T”

我的问题是在第 3 步,我收到错误:“尝试调用表值”

谁能告诉我如何在c中调用表格?

4

1 回答 1

2

卢阿

t = {}
setmetatable(t, { __call = function() print("calling the table") end })
pcall(t)

C 等效项(未经测试,但应该可以)

int mtcall(lua_State* L) {
    printf("calling the table\n");
    return 0;
}

int mainchunk(lua_State* L) {
    lua_newtable(L);                    // stack : t
    lua_newtable(L);                    // stack : t, mt
    lua_pushcfunction(L, &mtcall);      // stack : t, mt, &mtcall
    lua_setfield(L, -2, "__call");      // mt.__call = &mtcall || stack : t, mt
    lua_setmetatable(L, -2);            // setmetatable(t, mt) || stack : t
    if (lua_pcall(L, 1, 0) != 0)        // in case of error there will be an error string on the stack. Pop it out.
        lua_pop(L, 1);
    return 0;
}
于 2016-10-23T00:58:20.347 回答