推一个Lua表 [英] Pushing a Lua table

查看:138
本文介绍了推一个Lua表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C 中创建了一个Lua表,但我不知道如何将该表推到堆栈顶部,所以我可以将它传递给Lua函数。

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.

有没有人知道如何做?

这是我目前的代码:

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 ]


推荐答案

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

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

这篇关于推一个Lua表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆