Pushing a Lua table

后端 未结 3 1108
无人共我
无人共我 2021-02-14 13:13

I have created a Lua table in C, but I\'m not sure how to push that table onto the top of a stack so I can pass it to a Lua function.

Does anyone know h

相关标签:
3条回答
  • 2021-02-14 13:52

    Here's a quick helper function to push strings to the table

    void l_pushtablestring(lua_State* L , char* key , char* value) {
        lua_pushstring(L, key);
        lua_pushstring(L, value);
        lua_settable(L, -3);
    } 
    

    Here I use the helper function to create the table and pass it to a function

    // create a lua function
    luaL_loadstring(L, "function fullName(t) print(t.fname,t.lname) end");
    lua_pcall(L, 0, 0, 0);
    
    // push the function to the stack
    lua_getglobal(L, "fullName");
    
    // create a table in c (it will be at the top of the stack)
    lua_newtable(L);
    l_pushtablestring(L, "fname", "john");
    l_pushtablestring(L, "lname", "stewart");
    
    // call the function with one argument
    lua_pcall(L, 1, 0, 0);
    
    0 讨论(0)
  • 2021-02-14 14:06

    The table is already in the stack, where lua_newtable left it, isn't it?

    0 讨论(0)
  • 2021-02-14 14:07

    I made a small snippet open source that solves pushing simple Lua dictionary tables from C to Lua.

    You can check it out here, should work well.

    0 讨论(0)
提交回复
热议问题