Passing table with fields as an argument to Lua function from C++?

跟風遠走 提交于 2019-12-06 15:36:55

You can also use lua_setfield, which makes the code shorter and probably easier to read:

    lua_newtable(L);
    lua_pushinteger(L, 50);         // xpos = 50
    lua_setfield(L, -2, "xpos");
    lua_pushinteger(L, 80);         // ypos = 80
    lua_setfield(L, -2, "ypos");
    lua_pushstring(L, "hello");     // message = "hello"
    lua_setfield(L, -2, "message");

I'm not sure whether I understand the question correctly. If you want strings as keys in the table, then just push strings instead of numbers.

#include <iostream>

#include <lua.hpp>

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    char const script[] = "function test(t)\n"
                          "    print(t.xpos)\n"
                          "    print(t.ypos)\n"
                          "    print(t.message)\n"
                          "end";

    if (luaL_dostring(L, script) != 0) {
        std::cerr << lua_tostring(L, -1) << '\n';
        lua_close(L);
        return 1;
    }

    lua_getglobal(L, "test");
    if (lua_isfunction(L, -1)) {
        lua_newtable(L);
        // xpos = 50
        lua_pushstring(L, "xpos");
        lua_pushinteger(L, 50);
        lua_settable(L, -3);
        // ypos = 80
        lua_pushstring(L, "ypos");
        lua_pushinteger(L, 80);
        lua_settable(L, -3);
        // message = "hello"
        lua_pushstring(L, "message");
        lua_pushstring(L, "hello");
        lua_settable(L, -3);

        if (lua_pcall(L, 1, 0, 0) != 0) {
            std::cerr << "lua:" << lua_tostring(L, -1) << '\n';
            lua_close(L);
            return 1;
        }
    }

    lua_close(L);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!