Lesson 10 of 10

Turning a table into a string

Goal

Recursion and a fixed key order

01

Explanation

print(save) only prints something like table: 0x…, but you need the table as readable text to save the game, or to see its state while you track down a bug. Since a table can hold tables that hold more tables, the answer is a function that calls itself. It converts a simple value directly, and writes each entry of a table as key = followed by the result of calling serialize on its value.

Sort the keys before you write them, because pairs guarantees no order. If you don't, the same state comes out as two different strings from one run to the next, and you can't compare two save files or write a test that matches the text. Output in this form is valid Lua code as long as the string keys are ordinary names, so load("return " .. text)() turns it back into a table.

Watch out for a table that mixes numeric and string keys, like { "sword", gold = 50 }. If you call table.sort without a comparison function, it throws attempt to compare when it compares a number with a string. So write a comparison function that puts numbers before strings and compares each type only with its own kind.

02

Your task

Write serialize(value) so it returns a string in double quotes, a number or a boolean the way tostring gives it, and a table between {} with its entries separated by ", ". Write a numeric key in the form [1] = and a string key in the form gold = , with the numbers first in ascending order, then the strings in alphabetical order. So the table { "sword", gold = 50 } becomes this string: {[1] = "sword", gold = 50}.

Checks

5 checks
  1. Simple values are written correctly
  2. The table's keys are sorted
  3. Numeric keys are in brackets and come before string keys
  4. Nested and empty tables are written correctly
  5. The string turns back into a table with load
03

Hints

0/3
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.