Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- save.lua
- return {
- -- Table: {1}
- {
- ["inventory"]={2},
- ["name"]="Dark dude",
- },
- -- Table: {2}
- {
- "sword",
- "hammer",
- "shield",
- },
- }
- // main.cpp
- #include <iostream>
- #include <LuaBridge.h>
- #include <string>
- #include <vector>
- using namespace luabridge;
- std::vector<std::string> inventory;
- std::string name;
- void loadData();
- void showData();
- void saveData();
- int main() {
- loadData();
- showData();
- saveData();
- system("pause");
- }
- void loadData() {
- lua_State* L = luaL_newstate();
- luaL_openlibs(L);
- luaL_dofile(L, "serialize.lua");
- LuaRef table = getGlobal(L, "table");
- LuaRef load = table["load"];
- LuaRef playerTable = load("save.lua");
- LuaRef inventoryArray = playerTable["inventory"];
- for (int i = 1; i < inventoryArray.length() + 1; ++i) {
- inventory.push_back(inventoryArray[i]);
- }
- name = playerTable["name"].cast<std::string>();
- }
- void showData() {
- std::cout << "Name:" << name << std::endl;
- std::cout << "Inventory:" << std::endl;
- for (int i = 0; i < inventory.size(); ++i) {
- std::cout << ">" << inventory[i] << std::endl;
- }
- }
- void saveData() {
- lua_State* L = luaL_newstate();
- luaL_openlibs(L);
- luaL_dofile(L, "serialize.lua");
- LuaRef table = getGlobal(L, "table");
- LuaRef saveFunction = table["save"];
- LuaRef playerTable = newTable(L);
- LuaRef inventoryTable = newTable(L);
- playerTable["inventory"] = inventoryTable;
- playerTable["name"] = name;
- for (int i = 0; i < inventory.size(); ++i) {
- inventoryTable[i + 1] = inventory[i];
- }
- try {
- saveFunction(playerTable, "save.lua");
- }
- catch (const LuaException& e) {
- std::cout << e.what();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement