如何从字符串创建lua表?

  • 本文关键字:lua 创建 字符串 c++ c lua
  • 更新时间 :
  • 英文 :


我有一个c函数,用于将表返回给lua,但是该表是从字符串创建的,而不是lua_newtable,该怎么做?

int GetTable(lua_State* L)
{
//this string is generated at runtime, so i can not use lua_newtable
const char* TableFromStr = "{a = 123, b = 456, d = {x = 1, y = 9} }";
//i want to push the table to the top stack
luaL_loadstring(L, TableFromStr);
//return 1 table, lua code can get the table
return 1;
}

你必须使用luaL_dostring

https://www.lua.org/manual/5.1/manual.html#luaL_dostring

如果您使用的是 Lua 5.1,请确保正确定义luaL_dostring。请参阅:http://lua-users.org/lists/lua-l/2006-04/msg00218.html

在Lua 5.1中,luaL_dostring被定义为luaL_loadstring(L, s) || lua_pcall(L, 0, 0, 0)

因此,它忽略了回报。

试试这个:

#undef luaL_dostring
#define luaL_dostring(L,s)       (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))

您可能还必须在字符串前面加上return

最新更新