Add to save table (SOLVED)

Hi,

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’.

Can you show the code for this part and on which line the stacktrace and error message points? Have you tried the debugger btw?

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?

Why does one say MODULE.data.xp and the other MODULE.reward (without the data part)?

Oops! That was a typing error. I corrected it.
Other than that, the error still persist.

I’m unable to spot the problem. What if you delete the save file on disk and then try?

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.

You must be doing something wrong. Please zip a minimal example and share it here.

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.

1 Like