9.Lua调用c++函数获取返回值

时间:2021-10-04 00:10:40
1.Lua_pushstring(l,re); lua_pushnumber(l,123);//压入栈顶
c++: int CTestRe(lua_State *L) { lua_pushstring(L,"return value"); //在吧字符串压倒栈顶 return 1; //作为返回值传递给Lua,返回1个 } /main lua_register(lua,"CTestRe",CTestRe);
lua: local re = CTestRe(); print("re = "..re);


2.Lua调用c++返回表(示例返回对象) lua_newtable(l);//创建一个表格,放在栈顶 lua_pushstring(l,"name");//艳茹Key lua_pushstring(l,"ccname");//压入value //弹出Key,vlue,并设置到表,表在栈顶了作为返回值 lua_settable(l,-3);
c++: int CTestRe(lua_State *L) { lua_newtable(L); //插入key value lua_pushstring(L,"name"); lua_pushstring(L,"xiaoming"); lua_settable(L,-3);//将值写入表中,注意这里讲值放入表中之后会将上面两个出栈 return 1; //注意这里要返回 } /main lua_register(lua,"CTestRe",CTestRe);
lua: local tab= CTestRe(); print("name :"..tab["name"]);
传递多个表值:
c++改为: int CTestRe(lua_State *L) { lua_newtable(L); //插入key value lua_pushstring(L,"name"); lua_pushstring(L,"xiaoming"); lua_settable(L,-3);//将值写入表中,注意这里讲值放入表中之后会将上面两个出栈
lua_pushstring(L,"age"); lua_pushnumber(L, 21); lua_settable(L,-3);//注意这里还是-3 } //main //传递多个表值 lua_register(L, "CTestReTableN", CTestReTableN);
lua改为; local tab= CTestReTableN(); print("name :"..tab["name"]); print("age:"..tab["arg"]); 9.Lua调用c++函数获取返回值