使用Lua C API从表中提取用户数据。
我使用lua c api在表格中循环变量,如下所示。
lua脚本:
array = {0,1,2,3}
lua c api:
} lua_pushnil(l); while(lua_next(l,-2)){
int value =(int)lua_tonumber(l,-1);
printf("%d \n",value);
lua_pop(l,1);
} ```
我可以获得结果
0
1
2
3
然后我想将一些userdata对象放入表中,然后在c api中循环它们。
lua脚本
foo0 = Foo.new(“fred0”) foo1 = Foo.new(“fred0”) foo2 = Foo.new(“fred0”) foo3 = Foo.new(“fred0”) array = {foo0,foo1,foo2,foo3}
lua c api
extern“C” { #include“lua.h” #include“lauxlib.h” #include“lualib.h” }
#include
#include
class Foo { public: Foo(const std ::string&name):name(name) { std ::cout <<“Foo is born”<< std ::endl; }
std ::string Add(int a,int b)
{
std ::stringstream ss;
ss << name <<“:”<< a <<“+”<< b <<“=”<<(a + b);
返回ss.str();
}
~Foo()
{
std ::cout <<“Foo is gone”<< std ::endl;
}
std ::string name;
};
int l_Foo_constructor(lua_State * l) { const char * name = luaL_checkstring(l,1);
Foo ** udata =(Foo **)lua_newuserdata(l,sizeof(Foo *));
* udata = new Foo(name);
luaL_getmetatable(l,“luaL_Foo”);
lua_setmetatable(l,-2);
返回1;
}
Foo * l_CheckFoo(lua_State * l,int n) { 返回*(Foo **)luaL_checkudata(l,n,“luaL_Foo”); }
int l_Foo_add(lua_State * l) {
返回1;
}
int l_Foo_destructor(lua_State * l) { Foo * foo = l_CheckFoo(l,1); delete foo;
返回0;
}
void RegisterFoo(lua_State * l) { luaL_Reg sFooRegs [] = { {“new”,l_Foo_constructor}, {“add”,l_Foo_add}, {“__gc”,l_Foo_destructor}, {NULL,NULL} };
luaL_newmetatable(l,“luaL_Foo”);
luaL_register(l,NULL,sFooRegs);
lua_pushvalue(l,-1);
lua_setfield(l,-1,“__index”);
lua_setglobal(l,“Foo”);
}
int main() { lua_State * l = luaL_newstate(); luaL_openlibs(l); RegisterFoo(l);
int erred = luaL_dofile(l,“/Volumes/Work/CODE/Test/testStatic/testStatic/kami.txt”);
if(erred)
std ::cout << “Lua error:”<< luaL_checkstring(l,-1)<< std ::endl;
lua_getglobal(l,“array”);
if(lua_isnil(l,-1)){
//return std::vector();
}
lua_pushnil(l);
std ::vector <Foo *> v;
while(lua_next(l,-2)){
Foo * foo = l_CheckFoo(l,-1); //此行不起作用
//
//
//
//
//我不知道在这里该如何操作。
//
//
//
//
//v.push_back(foo);
lua_pop(l,1);
}
// for(Foo * theValue:v) // { // printf(“==>%s”,theValue->name.c_str()); // }
lua_close(l);
返回0;
}
```
如何从表中提取userdata? 请帮帮我,谢谢。
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
最后我自己解决了它。
应该改为
void *hehe = lua_touserdata(l, -1); Foo **haha = (Foo **)hehe; Foo *f = *haha; printf("%s \n", f->name.c_str());