How would you go about adding new values to an existing Lua table without getting a nil.
I had this:
local save = sys.get_save_file("com.example.game","data")
local player_data = sys.load(save)
MODULE.data =
{
highscore = 0,
xp = 0,
}
function MODULE.set()
if not next(player_data) then
MODULE.data.highscore = 0
MODULE.data.xp = 0
MODULE.save()
else
MODULE.data.highscore = player_data.highscore
MODULE.data.xp = player_data.xp
end
end
function MODULE.save()
sys.save(save, MODULE.data)
end
The problem is that whenever I want to add more save options to my MODULE.data for example reward = 0 and then in my MODULE.set() if not next then MODULE.data.reward = 0 else MODULE.data.reward = player_data.reward or 0 but Iâm getting an attempt to index field ârewardâ.
So there is already a lua table file on the device but I want to add more save options:
function MODULE.set()
if not next(player_data) then
MODULE.data.highscore = 0
MODULE.data.xp = 0
MODULE.data.reward = 0 --this is a new save option
MODULE.save()
else
MODULE.data.highscore = player_data.highscore
MODULE.data.xp = player_data.xp
MODULE.data.reward = player_data.reward or 0
end
end
This part gives me the error:
MODULE.data.reward = player_data.reward or 0
Is it because the data was already created without the reward and now that I want to add the reward save it does not recognize the reward from the save file?
As I want to add more features in my game there is more things that I need to keep track of and by adding new data to the table causing the error of attempt to index nil.
Everything works fine if there is no save file on the disk but if there is a save file on the disk and I want to add more feature to save then It does not recognize the new data but only the old once.
Yes, I understand that. But you must be doing something wrong.
sys.load(âfoobarâ) will load the serialized Lua table from the file âfoobarâ and return it. You can then do whatever you want with the table (add keys, change keys, remove keys). It is a normal table.
sys.save(âfoobarâ, t) will serialize and save the Lua table âtâ to file âfoobarâ. âtâ can be the table loaded using sys.load() or another table. It doesnât matter.