passing a lua table from C++ to .Lua script

橙三吉。 提交于 2019-12-11 01:29:56

问题


I have spent the past 6 hours trying to solve this ! and i coulnt get anywhere :s

I want to be able to create a lua table in a c++ file and then pass that to a lua script file, which has the following lua function:

function MTable (t) 
local n=#t
    for i=1,n do 
      print(t[i]) 
    end
end

i dynamically created a one dimensional array with two strings:

 lua_newtable(L);
 lua_pushstring(L,"10.10.1.1");
 lua_pushstring(L,"10.10.1.2");
 lua_rawseti(L,-3,2);
 lua_rawseti(L,-2,1);

so now i have the table on top of the stack. I have verified it by writting this : if( lua_istable(L,lua_gettop(L)))` which returned 1, which means it is a table.

then I did this:

lua_getglobal(L, "MTable");    // push the lua function onto the stack

uint32_t   result = lua_pcall(L, 1, 0, 0);  //argument 1 is for the table
 if (result) {
 printf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
         exit(1);
}

so I got that error: Failed to run script: attempt to call a table value

Kindly note that the file has several other functions that i am calling successfully from c++.

can somebody please help me solve this error ? can this be a bug from LUA? cz i followed the steps very correctly...i guess !


回答1:


The function has to be first on the stack, before the args.

You can either:

  1. push the function to call on the stack before generating the table, e.g.:

    lua_getglobal(L, "MTable");
    ...generate table on stack...
    int result = lua_pcall(L, 1, 0, 0);
    
  2. Do in the order you do now, and then just swap the arg and the function prior to doing the pcall:

    ...generate table on stack...
    lua_getglobal(L, "MTable");
    lua_insert (L, -2);   // swap table and function into correct order for pcall
    int result = lua_pcall(L, 1, 0, 0);
    


来源:https://stackoverflow.com/questions/10670094/passing-a-lua-table-from-c-to-lua-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!