Advertisement
eliasdaler

C++/Lua table serialization

Aug 4th, 2014
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. -- save.lua
  2. return {
  3. -- Table: {1}
  4. {
  5.    ["inventory"]={2},
  6.    ["name"]="Dark dude",
  7. },
  8. -- Table: {2}
  9. {
  10.    "sword",
  11.    "hammer",
  12.    "shield",
  13. },
  14. }
  15.  
  16. // main.cpp
  17.  
  18. #include <iostream>
  19. #include <LuaBridge.h>
  20. #include <string>
  21. #include <vector>
  22.  
  23. using namespace luabridge;
  24.  
  25. std::vector<std::string> inventory;
  26. std::string name;
  27. void loadData();
  28. void showData();
  29. void saveData();
  30.  
  31. int main() {
  32.     loadData();
  33.     showData();
  34.     saveData();
  35.     system("pause");
  36. }
  37.  
  38. void loadData() {
  39.     lua_State* L = luaL_newstate();
  40.     luaL_openlibs(L);
  41.     luaL_dofile(L, "serialize.lua");
  42.     LuaRef table = getGlobal(L, "table");
  43.     LuaRef load = table["load"];    
  44.     LuaRef playerTable = load("save.lua");
  45.     LuaRef inventoryArray = playerTable["inventory"];
  46.     for (int i = 1; i < inventoryArray.length() + 1; ++i) {
  47.         inventory.push_back(inventoryArray[i]);
  48.     }
  49.     name = playerTable["name"].cast<std::string>();
  50. }
  51.  
  52. void showData() {
  53.     std::cout << "Name:" << name << std::endl;
  54.     std::cout << "Inventory:" << std::endl;
  55.     for (int i = 0; i < inventory.size(); ++i) {
  56.         std::cout << ">" << inventory[i] << std::endl;
  57.     }
  58. }
  59.  
  60. void saveData() {
  61.     lua_State* L = luaL_newstate();
  62.     luaL_openlibs(L);
  63.     luaL_dofile(L, "serialize.lua");
  64.     LuaRef table = getGlobal(L, "table");
  65.     LuaRef saveFunction = table["save"];
  66.     LuaRef playerTable = newTable(L);
  67.     LuaRef inventoryTable = newTable(L);
  68.     playerTable["inventory"] = inventoryTable;
  69.     playerTable["name"] = name;
  70.     for (int i = 0; i < inventory.size(); ++i) {
  71.         inventoryTable[i + 1] = inventory[i];
  72.     }
  73.     try {
  74.         saveFunction(playerTable, "save.lua");
  75.     }
  76.     catch (const LuaException& e) {
  77.         std::cout << e.what();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement