sys_save_load.script 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. local function load_highscore()
  2. local filename = sys.get_save_file("sys_save_load", "highscore") -- <1>
  3. local data = sys.load(filename) -- <2>
  4. return data.highscore or 0 -- <3>
  5. end
  6. local function save_highscore(highscore)
  7. local filename = sys.get_save_file("sys_save_load", "highscore")
  8. sys.save(filename, { highscore = highscore }) -- <4>
  9. end
  10. local function update_labels(score, highscore)
  11. label.set_text("score#score", tostring(score))
  12. label.set_text("score#highscore", "HIGH SCORE\n" .. tostring(highscore))
  13. end
  14. function init(self)
  15. msg.post(".", "acquire_input_focus")
  16. self.score = 0
  17. self.highscore = load_highscore()
  18. update_labels(self.score, self.highscore)
  19. end
  20. function update(self, dt)
  21. if self.pressed then
  22. self.score = self.score + math.ceil(100 * dt)
  23. update_labels(self.score, self.highscore)
  24. end
  25. end
  26. function on_input(self, action_id, action)
  27. if action_id == hash("touch") then
  28. if action.pressed then
  29. self.score = 0
  30. self.pressed = true
  31. elseif action.released then
  32. self.pressed = false
  33. if self.score > self.highscore then
  34. self.highscore = self.score
  35. save_highscore(self.highscore)
  36. update_labels(self.score, self.highscore)
  37. end
  38. end
  39. end
  40. end
  41. --[[
  42. 1. Get an application specific path for the file "highscore"
  43. 2. Load saved data.
  44. 3. The returned data is a Lua table with the saved values or an empty table if nothing has been saved.
  45. 4. Save data. The data to save must be stored in a Lua table.
  46. --]]