Lesson 10 of 10

Saving and loading the game

Goal

From table to text and back without load

01

Explanation

Saving a game means turning its state into text that gets written to a file or a database, and then rebuilding the state from that text when the player comes back. The shortest route in Lua is to write the table out as code like {hp=100} and run it with load, and that's exactly what you must not do. The save file is in the player's hands, and anyone who can edit it can put code in it for the server to run. So here you'll parse the text yourself.

A simple format is one line per value, with the key, then the value's type, then the value, like gold=n:250 and name=s:Layan. A nested table is written with a dotted key like pos.x=n:3. A string that contains a newline has to be encoded before it's written, or the file breaks at that line.

Watch the types. If you write everything with tostring and read it back as text, you get "false" instead of false, and any string counts as true in a Lua condition, so the dead player comes back to life. In the same way, "007" turns into the number 7 if you convert everything that looks like a number. That's why you store the type along with the value.

02

Your task

Write serialize(data), which returns a string, and deserialize(text), which returns a table equal to the original. This table's keys are names, and its values are numbers, strings and booleans, or nested tables one level deep that hold those same types. The types must come back as they were, and strings must come back intact even if they contain newlines or =, all without using load.

Checks

6 checks
  1. A one-level table comes back as it was
  2. A number comes back as a number and a string as a string
  3. The value false comes back as false, not as a string
  4. A nested table comes back with its keys
  5. A string with newlines and symbols comes back intact
  6. Loading doesn't use load
03

Hints

0/3
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.