| 54 | } |
| 55 | |
| 56 | int LUAPersistentTable::Set(lua_State *pState) { |
| 57 | SCRIPT_CALLBACK(LUAPersistentTable, table); |
| 58 | const char* name = SCRIPT_READ_STRING(NULL); |
| 59 | if (name) { |
| 60 | Int8 removing = SCRIPT_NEXT_TYPE==LUA_TNIL ? 1 : 0; |
| 61 | string path; |
| 62 | FileSystem::MakeFolder(String::Format(path, table.path, '/', name)); |
| 63 | |
| 64 | lua_getmetatable(pState, 1); |
| 65 | lua_getfield(pState, -1, "|items"); |
| 66 | lua_getfield(pState, -1, name); // old value |
| 67 | |
| 68 | if (!removing) { |
| 69 | if (lua_istable(pState, -1)) { |
| 70 | SCRIPT_ERROR("Complex type exists already on ", path, ", for secure reasons delete explicitly this entry with a nil assignation before override") |
| 71 | removing = -1; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | if (removing>=0) { |
| 76 | if (SCRIPT_NEXT_TYPE==LUA_TTABLE) { |
| 77 | |
| 78 | lua_pushvalue(pState, 2); // name |
| 79 | Script::NewObject<LUAPersistentTable,LUAPersistentTable>(pState,*new LUAPersistentTable(table.persistentData, path)); |
| 80 | |
| 81 | // table iteration |
| 82 | lua_pushnil(pState); // first key |
| 83 | while (Script::Next(pState, 3) != 0) { |
| 84 | // uses 'key' (at index -2) and 'value' (at index -1) |
| 85 | lua_pushvalue(pState, -2); // duplicate key |
| 86 | lua_pushvalue(pState, -2); // duplicate value |
| 87 | lua_settable(pState, -5); |
| 88 | lua_pop(pState, 1); |
| 89 | } |
| 90 | |
| 91 | // memory |
| 92 | lua_rawset(pState, -4); |
| 93 | |
| 94 | } else { |
| 95 | // Primitive type! |
| 96 | Exception ex; |
| 97 | bool success = false; |
| 98 | if (removing) { |
| 99 | if ((success = table.persistentData.remove(ex, path)) && !lua_isnil(pState, -1) && !lua_istable(pState, -1)) |
| 100 | --table.count; |
| 101 | } else { |
| 102 | UInt32 size(0); |
| 103 | const UInt8* value = Serialize(pState,3,size); |
| 104 | if((success = table.persistentData.add(ex, path, value , size)) && lua_isnil(pState, -1)) |
| 105 | ++table.count; |
| 106 | } |
| 107 | if (success) { |
| 108 | // memory |
| 109 | lua_pushvalue(pState, 2); // name |
| 110 | lua_pushvalue(pState, 3); // value |
| 111 | lua_rawset(pState, -4); |
| 112 | if (ex) |
| 113 | SCRIPT_WARN("Database entry ", path, " writing, ", ex.error()) |