• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Solved Send std::map to LUA as a table

Snavy

Bakasta
Senator
Joined
Apr 1, 2012
Messages
1,249
Solutions
71
Reaction score
621
Location
Hell
TFS: 1.3

I have the following std::map and I am trying to push this to lua.
C++:
std::map<AccountType_t, std::vector<std::string>> finalMap;
desired result & example usage:
Lua:
local result = resultFromMethod() -- finalMap
for i=1, #result[ACCOUNT_TYPE_NORMAL] do
    local tableOfStrings = result[ACCOUNT_TYPE_NORMAL][i]
    for j=1, #tableOfStrings do
        print("cool string here " .. tableOfStrings[j])
    end
end

I haven't fully understood how the lua_ methods work yet.

How could I achieve the desired result?

EDIT:
I have looked at lua reference manual and written the following but I'm not sure if this is the right path.

C++:
    lua_createtable(L, finalMap.size(), 0);
  
    for (auto &ta: finalMap) {
        lua_setfield(L, lua_gettop(L), ta.first);    // create KEY ?
        lua_settable(L, lua_gettop(L));              // set a table to key ? key = {} ? o.0
        lua_gettable(L, lua_gettop(L));              // get recently set table ( ? )
        for (auto &s: ta.second) {
            pushString(L, s);                        // push words from std::vector into the table (?)
        }
    }

EDIT 2 ( Solved ):

Came across davidm/lua2c (https://github.com/davidm/lua2c) and set it up with a sample lua code.
It generated the following:
Code:
  /* local mytbl = {
   *     [1] = {"asd","fdsa","pasd"},
   *     [2] = {"hes","zzz","fff"}
   * } */
  lua_createtable(L,0,2);
  lua_pushnumber(L,1);
  lua_createtable(L,3,0);
  lua_pushliteral(L,"asd");
  lua_rawseti(L,-2,1);
  lua_pushliteral(L,"fdsa");
  lua_rawseti(L,-2,2);
  lua_pushliteral(L,"pasd");
  lua_rawseti(L,-2,3);
  lua_rawset(L,-3);
  lua_pushnumber(L,2);
  lua_createtable(L,3,0);
  lua_pushliteral(L,"hes");
  lua_rawseti(L,-2,1);
  lua_pushliteral(L,"zzz");
  lua_rawseti(L,-2,2);
  lua_pushliteral(L,"fff");
  lua_rawseti(L,-2,3);
  lua_rawset(L,-3);
after modifying I ended up with :

C++:
    lua_createtable(L, finalMap.size(), 0);

    for (auto &ta: finalMap) {
        lua_pushnumber(L, ta.first);                 // inner table key
        lua_createtable(L, ta.second.size(), 0);     // create inner table

        uint32_t index = 0;
        for (auto &word: ta.second) {
            pushString(L, word);            // table element
            lua_rawseti(L, -2, ++index);    // table element index
        }

        lua_rawset(L, -3);
    }
 
Last edited:
Back
Top