简体   繁体   中英

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

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 !

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, eg:

     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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM