将带有字段的表作为参数从C++传递给 Lua 函数?
Passing table with fields as an argument to Lua function from C++?
我想知道如何用字段和值形成一个Lua表,这样我就可以把它作为参数传递给C++的Lua函数。
我知道如何使用索引形成一个表格,但我不知道如何从由字段和值组成的表格中形成表格。
例如,我想将此表作为C++的参数发送到Lua函数。
t = {xpos = 50, ypos = 80, message = 'hello'}
下面的代码是我能得到的最接近的代码,但它只是没有字段名称的索引表。
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
,这使得代码更短,可能更容易阅读:
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");
我不确定我是否正确理解了这个问题。 如果您希望字符串作为表中的键,则只需推送字符串而不是数字即可。
#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);
}
相关文章:
- C++Lua用户数据扰乱了Mathfu浮点值
- 使用 LuaBridge 或 Lua 将对象传递给 Lua 函数C++
- 将 Lua 函数块转换为 C 字符串
- 我可以从 lua 5.0.2 加载用 c++ 编写的 lua 5.3.5 dll 吗?
- 使用 lua 协程 API 和lua_close时出现分段错误
- 使用 C++ 自动 Lua 绑定
- 调用 lua 函数的地址为 C/C++?
- lua 5.0.2 模块和 5.3.5 有什么区别?
- 如何将 Lua 添加到C++项目
- 使用 Lua 中的C++库对象
- 如何在C++中将用户数据从一个 Lua 块传递到另一个块
- 如何使用重新定义的打印函数打印Lua表?
- Lua table in C++ dll
- 在运行时环境中使用 C++ w/ Lua
- 将shared_ptr传递给Lua
- luaL_len is missing in Lua 5.1
- 将向量传递给<struct> Lua 表
- 将 Lua 与 C++ DLL 结合使用
- Lua C API - 从C++分配和使用类的对象成员
- C++中最接近 Lua 表操作的东西是什么?