2

I am trying call a table using c API and Lua5.1.

I'm doing it by following steps:

  1. create a table "mt" that has __call metafunction
  2. create a table "newT" and set "mt" to "newT" metatable
  3. pcall "newT"

My problem is at step 3, I get the error: "attempt to call a table value"

Can anyone tell me how to call a table in c?

Fraser
  • 15,275
  • 8
  • 53
  • 104

1 Answers1

1

Lua

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

C equivalent (not tested, but should work)

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