推送 Lua 表

发布于 2024-09-28 18:24:00 字数 427 浏览 0 评论 0原文

我已经在C中创建了一个Lua表,但我不确定如何将该表推到堆栈顶部,以便我可以将其传递给Lua函数。

有谁知道该怎么做?

这是我当前的代码:

lua_createtable(state, libraries.size(), 0);
int table_index = lua_gettop(state);
for (int i = 0; i < libraries.size(); i++)
{
    lua_pushstring(state, libraries[i].c_str());
    lua_rawseti(state, table_index, i + 1);
}

lua_settable(state, -3);

[ Push other things ]
[ Call function ]

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 how to do this?

This is my current code:

lua_createtable(state, libraries.size(), 0);
int table_index = lua_gettop(state);
for (int i = 0; i < libraries.size(); i++)
{
    lua_pushstring(state, libraries[i].c_str());
    lua_rawseti(state, table_index, i + 1);
}

lua_settable(state, -3);

[ Push other things ]
[ Call function ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奈何桥上唱咆哮 2024-10-05 18:24:00

这是一个将字符串推送到表的快速辅助函数

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

这里我使用辅助函数来创建表并将其传递给函数

// 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);

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);
二货你真萌 2024-10-05 18:24:00

该表已经在堆栈中了,就是 lua_newtable 离开它的地方,不是吗?

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

玉环 2024-10-05 18:24:00

我开源了一个小片段,解决了将简单的 Lua 字典表从 C 推送到 Lua 的问题。

您可以在此处查看,应该可以正常工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文