SHARE
TWEET

Using Lua with C++ iterating over table examle

eliasdaler Feb 16th, 2016 412 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <string>
  3. #include <unordered_map>
  4.  
  5. extern "C" {
  6. #include "lua.h"
  7. #include "lauxlib.h"
  8. #include "lualib.h"
  9. }
  10. #include <LuaBridge.h>
  11.  
  12. std::unordered_map<std::string, luabridge::LuaRef> getKeyValueMap(const luabridge::LuaRef& table)
  13. {
  14.     using namespace luabridge;
  15.     std::unordered_map<std::string, LuaRef> result;
  16.     if (table.isNil()) { return result; }
  17.  
  18.     auto L = table.state();
  19.     push(L, table); // push table
  20.  
  21.     lua_pushnil(L);  // push nil, so lua_next removes it from stack and puts (k, v) on stack
  22.     while (lua_next(L, -2) != 0) { // -2, because we have table at -1
  23.         if (lua_isstring(L, -2)) { // only store stuff with string keys
  24.             result.emplace(lua_tostring(L, -2), LuaRef::fromStack(L, -1));
  25.         }
  26.         lua_pop(L, 1); // remove value, keep key for lua_next
  27.     }
  28.  
  29.     lua_pop(L, 1); // pop table
  30.     return result;
  31. }
  32.  
  33. int main()
  34. {
  35.     lua_State* L = luaL_newstate();
  36.     luaL_openlibs(L);
  37.  
  38.     luabridge::LuaRef table = luabridge::newTable(L);
  39.     table["someKey"] = 8;
  40.     table["someAnotherKey"] = "this is a string";
  41.  
  42.     // print the stuff
  43.     std::cout << "Here's what table contains:" << std::endl;
  44.     for (auto& pair : getKeyValueMap(table)) {
  45.         auto& key = pair.first;
  46.         auto& value = pair.second;
  47.  
  48.         std::cout << key << " = ";
  49.         if (value.isNumber()) {
  50.             std::cout << value.cast<int>();
  51.         } else if (value.isString()) {
  52.             std::cout << value.cast<std::string>();
  53.         }
  54.         std::cout << std::endl;
  55.     }
  56. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top