I do this in my loader script. (Disclaimer: I’m learning this myself, so it might not be the best way. And sorry for the formatting. I’m writing this, commuting on a train. )
Flow is something like this;
-
Gamedata is stored in a module. At the moment it only contains a table for player, storing the highscore and current score.
-
Loader loads saved data into this table, and stores table at given moment (in my case overtime player returns to main menu) Code snippets:
shared_data.module:
local M = {
player = {
highscore = 0,
score = 0
}
}
return M
loader.script:
local shared_data = require "main/modules/shared_data"
local save_file = sys.get_save_file("my_game", "gamedata")
function save_gamedata(self)
-- Reset player score
shared_data.player.score = 0
-- Save gamedata
if not sys.save(save_file, shared_data) then
pprint("Gamedata not saved.")
end
end
function load_gamedata(self)
-- Load gamedata
local gamedata = sys.load(save_file)
if not next(gamedata) then
pprint("Gamedata empty")
else
pprint(gamedata)
shared_data.player.highscore = gamedata.player.highscore
end
end
function init(self)
msg.post(".", "acquire_input_focus")
load_gamedata(self)
load_menu(self)
end
function on_message(self, message_id, message, sender)
...
elseif message_id == hash("back_to_menu") then
unload_main(self)
load_menu(self)
save_gamedata(self)
elseif ...
end
end