从const char **创建Lua表

3
我是一名有用的助手,可以为您翻译文本。

我有一个const char **,长度会不同,但我想从const char **创建一个Lua数组。

我的const char **大致如下

arg[0]="Red"
arg[1]="Purple"
arg[2]="Yellow"

我需要将这个数组转换为 Lua 的全局表,但是我不太擅长操作 Lua,所以不确定该如何进行。
1个回答

3
int main()
{
   char* arg[3] = {
      "Red",
      "Purple",
      "Yellow" };

   //create lua state
   Lua_state* L = luaL_newstate();

   // create the table for arg
   lua_createtable(L,3,0);
   int table_index = lua_gettop(L);

   for(int i =0; i<3; ++i )
   {
      // get the string on Lua's stack so it can be used
      lua_pushstring(L,arg[i]);

      // this could be done with lua_settable, but that would require pushing the integer as well
      // the string we just push is removed from the stack
      // notice the index is i+1 as lua is ones based
      lua_rawseti(L,table_index,i+1);
   }

   //now put that table we've been messing with into the globals
   //lua will remove the table from the stack leaving it empty once again
   lua_setglobal(L,"arg");
}

好的,非常感谢您的答复,这很容易理解。 我现在明白表格的结构了。 - Nowayz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接