Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <unordered_map>
- extern "C" {
- #include "lua.h"
- #include "lauxlib.h"
- #include "lualib.h"
- }
- #include <LuaBridge.h>
- std::unordered_map<std::string, luabridge::LuaRef> getKeyValueMap(const luabridge::LuaRef& table)
- {
- using namespace luabridge;
- std::unordered_map<std::string, LuaRef> result;
- if (table.isNil()) { return result; }
- auto L = table.state();
- push(L, table); // push table
- lua_pushnil(L); // push nil, so lua_next removes it from stack and puts (k, v) on stack
- while (lua_next(L, -2) != 0) { // -2, because we have table at -1
- if (lua_isstring(L, -2)) { // only store stuff with string keys
- result.emplace(lua_tostring(L, -2), LuaRef::fromStack(L, -1));
- }
- lua_pop(L, 1); // remove value, keep key for lua_next
- }
- lua_pop(L, 1); // pop table
- return result;
- }
- int main()
- {
- lua_State* L = luaL_newstate();
- luaL_openlibs(L);
- luabridge::LuaRef table = luabridge::newTable(L);
- table["someKey"] = 8;
- table["someAnotherKey"] = "this is a string";
- // print the stuff
- std::cout << "Here's what table contains:" << std::endl;
- for (auto& pair : getKeyValueMap(table)) {
- auto& key = pair.first;
- auto& value = pair.second;
- std::cout << key << " = ";
- if (value.isNumber()) {
- std::cout << value.cast<int>();
- } else if (value.isString()) {
- std::cout << value.cast<std::string>();
- }
- std::cout << std::endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement