将带有字段的表作为参数传递给C ++的Lua函数? [英] Passing table with fields as an argument to Lua function from C++?
本文介绍了将带有字段的表作为参数传递给C ++的Lua函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何用字段和值组成一个Lua表,以便可以将它作为参数传递给C ++的Lua函数.
I would like to know how to form a Lua table with fields and values so I can pass it as an argument to a Lua function from C++.
我知道如何使用索引来构成表格,但是我不知道如何从由字段和值组成的表格中构成.
I know how to form a table using indices but I don't know how to from a table made of fields and values.
例如,我想将此表作为C ++的参数发送给Lua函数.
For example, I want to send this table to a Lua function as an argument from C++.
t = {xpos = 50, ypos = 80, message = 'hello'}
下面的代码是我能得到的最接近的代码,但这只是没有字段名的索引表.
The below code is the closest I could get, but it's just indexed table with no field name.
lua_getglobal(L, "myLuaFunc");
if (lua_type(L, -1) == LUA_TFUNCTION)
{
lua_newtable(L);
lua_pushinteger(L, 1);
lua_pushnumber(L, 50);
lua_pushinteger(L, 2);
lua_pushnumber(L, 80);
lua_pushinteger(L, 3);
lua_pushstring(L, 'hello');
lua_settable(L, -3);
if (lua_pcall(L, 1, 0, 0))
std::cout << "Error : " << lua_tostring(L, -1) << std::endl;
}
lua_pop(L, 1);
推荐答案
您还可以使用lua_setfield
,它使代码更短并且更容易阅读:
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");
这篇关于将带有字段的表作为参数传递给C ++的Lua函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文