我遵循了这个样板示例:http : //www.matrix44.net/blog/?p=456
我能够将字符串从 C 发送到 Lua,但是当我传递一个结构体时出现错误(我使用了 lua_newuserdata)。
//s = (ST*) malloc ( sizeof(ST) );
// lua_pushlightuserdata(state, s);
s = lua_newuserdata(state, sizeof(ST));
s->a=11;
s->b=12;
printf ( "s = %p \n", s ); // Prints 0x80a708
result = lua_pcall(state, 0, LUA_MULTRET, 0);
Run Code Online (Sandbox Code Playgroud)
print(foo) --> Prints 0x80a708
io.write("received has:\n", foo.a); --> ERROR : Failed to run script: script.lua:1: attempt to index global 'foo' (a userdata value)
Run Code Online (Sandbox Code Playgroud)
如何将缓冲区转换为结构/表记录?
最终,我的 C 程序不知道结构,它只会将缓冲区传递给 Lua,而 Lua 知道该结构并且需要在那里进行转换。
谢谢, PS:脚本和 C 程序的 printf 匹配(0x80a708),我可以投射吗??
Lua 没有结构,它有表。
Userdata 是一种向 Lua 传递不透明数据的便捷方式,但 Lua 将无法看到内部。Userdata 仅在您将其传递回 C++ 并且您有办法确定它是什么(基本上将其转换为正确的类型)时才有用。
Lua 表最接近 C++ 中的结构。你可以这样写:
lua_newtable(state);
lua_pushnumber(state, s->a);
lua_setfield(state, -2, "a");
lua_pushnumber(state, s->b);
lua_setfield(state, -2, "b");
Run Code Online (Sandbox Code Playgroud)
有了这个,现在你可以在 lua 中引用它:
print(foo.a); -- this will now print 11
Run Code Online (Sandbox Code Playgroud)