c++lualua-c++-connection

Simplest lua function that returns a vector of strings


I need a very simple c++ function that calls a lua function that returns an array of strings, and stores them as a c++ vector. The function can look something like this:

std::vector<string> call_lua_func(string lua_source_code);

(where lua source code contains a lua function that returns an array of strings).

Any ideas?

Thanks!


Solution

  • Here is some source that may work for you. It may need some more polish and testing. It expects that the Lua chunk is returning the array of strings, but with slight modification could call a named function in the chunk. So, as-is, it works with "return {'a'}" as a parameter, but not "function a() return {'a'} end" as a parameter.

    extern "C" {
    #include "../src/lua.h"
    #include "../src/lauxlib.h"
    }
    
    std::vector<string> call_lua_func(string lua_source_code)
    {
      std::vector<string> list_strings;
    
      // create a Lua state
      lua_State *L = luaL_newstate();
      lua_settop(L,0);
    
      // execute the string chunk
      luaL_dostring(L, lua_source_code.c_str());
    
      // if only one return value, and value is a table
      if(lua_gettop(L) == 1 && lua_istable(L, 1))
      {
        // for each entry in the table
        int len = lua_objlen(L, 1);
        for(int i=1;i <= len; i++)
        {
          // get the entry to stack
          lua_pushinteger(L, i);
          lua_gettable(L, 1);
    
          // get table entry as string
          const char *s = lua_tostring(L, -1);
          if(s)
          {
            // push the value to the vector
            list_strings.push_back(s);
          }
    
          // remove entry from stack
          lua_pop(L,1);
        }
      }
    
      // destroy the Lua state
      lua_close(L);
    
      return list_strings;
    }