Tiny Shelf 37 · Read an older or damaged scrapbook

Tiny Shelf Studio · Lesson 37 of 50 · Intermediate to advanced · About 35 min

Your first game stored one badge. A newer scrapbook can hold several. Write a bridge for old data and give unexpected formats a clear result.

Miniature packaging workshop with coloured paper models, tools and a teal cutting mat.
What you’ll make Validate a save and migrate a known older structure without modifying the source record.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/36 when the lesson builds on prior work, or copy the checkpoints/37 folder to try this lesson on its own. Read the file names in the steps before editing.

Read the record. Check that it is a dictionary. → Recognise version. Read the path this game knows. → Clean stamps. Keep valid IDs once. → Preserve unknown files. Skip updates when checks fail.
Read the record → Recognise version → Clean stamps → Preserve unknown files
Godot checkpoint window for Read an older or damaged scrapbook
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Variant, is, Dictionary.get, Array[String], return.

  1. Open the design bench

    Import this checkpoint's project.godot into Godot 4.7.2. Open main.gd from FileSystem. Press F5 for the starting view and F8 to stop it. Keep a copy to undo experiments.

    Why it works The checkpoint scene attaches main.gd to a Control. Each test starts from that known version, so compare one change with the original.

  2. Try the two versions

    Tap Version 1 and Version 2. In the older case the source contains a Boolean. In the newer case the source contains an array.

    var version: Variant = source.get("format", 0)

    Why it works The practice fixtures represent data already read from disk. upgrade handles data in memory before any decision to write.

  3. Guard the record shape

    Find the first if. Temporarily call inspect("empty") from _ready and read the result. Restore the original input before moving on.

    if not source is Dictionary:

    Why it works A Variant can hold different types. Checking for Dictionary first avoids reading a string as a record.

  4. Migrate the earned flag

    Read the version-one return and change the test flag to false. Compare the number of restored stamps.

    return {"format": CURRENT_FORMAT, "stamps": ["first_display"] if old_flag else []}

    Why it works The expression returns the stable first_display ID only when the checked flag is true.

  5. Check, clean and deduplicate

    Tap Version 2 and read the displayed stamps. Add a duplicated ID and an unknown ID to its fixture, then try the button again.

    if value is String and value in VALID and value not in kept:

    Why it works One guard checks the type, the allowed catalogue and whether that stamp is already in the output.

  6. Refuse a file that needs newer code

    Tap Future version and Damaged file. Confirm both leave the original input untouched.

    if version != CURRENT_FORMAT or not source.get("stamps") is Array:

    Why it works The version and array checks run before the loop. An empty result means the app should preserve the source for later recovery, without applying badge updates.

Watch the values change

  1. Tap Version 1 earned is true.
    What you see. The upgrade returns first_display in format 2.
  2. Tap Version 2 The raw list contains an unknown ID and a repeated ID.
    What you see. The screen displays only first_display and window_crew.
  3. Tap Future version 9 is greater than the current format.
    What you see. The test app applies no updates.

Predict before you run Will upgrade erase unknown_thing from the original array after removing it from the returned list?

Reveal the answer

No. The function builds a new list named kept. The input remains unchanged.

Complete checkpoint

A save laboratory showing which records migrate, which records clean successfully, and which records need attention.

main.gd

extends Control

const VALID := ["first_display", "rainbow_row", "window_crew"]
const CURRENT_FORMAT := 2
var status: Label
var stamps: Label
var version_note: Label

func _ready() -> void:
	title_page("SAVE FORMATS", "Read an older or damaged scrapbook", "Check the data shape before trying to show any stamp.")
	status = label("", Vector2(61, 227), 27, GOLD)
	stamps = label("", Vector2(62, 283), 18, SEA)
	version_note = label("", Vector2(62, 316), 16)
	place_button("Version 1", Vector2(62, 411), inspect.bind({"format": 1, "earned": true}))
	place_button("Version 2", Vector2(244, 411), inspect.bind({"format": 2, "stamps": ["first_display", "window_crew", "unknown", "window_crew"]}))
	place_button("Damaged file", Vector2(426, 411), inspect.bind({"format": 2, "stamps": "broken"}))
	place_button("Future version", Vector2(608, 411), inspect.bind({"format": 9, "stamps": ["first_display"]}))
	inspect({"format": 1, "earned": true})

func upgrade(source: Variant) -> Dictionary:
	if not source is Dictionary:
		return {}
	var version: Variant = source.get("format", 0)
	if not version is int:
		return {}
	if version == 1:
		var old_flag: Variant = source.get("earned", false)
		if not old_flag is bool:
			return {}
		return {"format": CURRENT_FORMAT, "stamps": ["first_display"] if old_flag else []}
	if version != CURRENT_FORMAT or not source.get("stamps") is Array:
		return {}
	var kept: Array[String] = []
	for value in source["stamps"]:
		if value is String and value in VALID and value not in kept:
			kept.append(value)
	return {"format": CURRENT_FORMAT, "stamps": kept}

func inspect(source: Variant) -> void:
	var result := upgrade(source)
	status.text = "SCRAPBOOK READY" if not result.is_empty() else "RECORD NEEDS ATTENTION"
	stamps.text = "Stamps · " + ", ".join(result["stamps"]) if not result.is_empty() else "No badge updates applied."
	version_note.text = "Read into format %d" % result["format"] if not result.is_empty() else "The original record is unchanged."

func _draw() -> void:
	backdrop()
	panel(Rect2(45, 170, 860, 192), Color("#244457"), GOLD)

const PAPER := Color("#fff4de")
const GOLD := Color("#f5bd79")
const SEA := Color("#9ddcd0")
const INK := Color("#172c3c")
const EDGE := Color("#54817f")

func title_page(unit: String, heading: String, subtitle: String) -> void:
	label("TINY SHELF STUDIO  /  " + unit, Vector2(44, 36), 14, GOLD)
	label(heading, Vector2(44, 65), 33)
	label(subtitle, Vector2(46, 119), 16, SEA)

func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:
	var item := Label.new()
	item.text = words
	item.position = at
	item.add_theme_font_size_override("font_size", pixels)
	item.add_theme_color_override("font_color", ink)
	add_child(item)
	return item

func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:
	var control := Button.new()
	control.text = words
	control.position = at
	control.custom_minimum_size = Vector2(width, 48)
	control.add_theme_font_size_override("font_size", 17)
	control.add_theme_color_override("font_color", PAPER)
	control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))
	control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))
	control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))
	control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))
	control.pressed.connect(action)
	add_child(control)
	return control

func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:
	var block := StyleBoxFlat.new()
	block.bg_color = fill
	block.border_color = edge
	block.set_border_width_all(line)
	block.set_corner_radius_all(8)
	return block

func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:
	draw_style_box(style(fill, edge), rect)

func backdrop() -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))
	panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))

func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:
	draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. const VALID := ["first_display", "rainbow_row", "window_crew"]All good stamps are stored as stable names. Reject any unknown product or badge code in this lab.
  3. const CURRENT_FORMAT := 2Creates a constant named CURRENT_FORMAT. The expression uses the whole number 2. Godot infers the type from the first value.
  4. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  5. var stamps: LabelDeclares stamps for later use. A colon followed by a type says which kind of value belongs here.
  6. var version_note: LabelDeclares version_note for later use. A colon followed by a type says which kind of value belongs here.
  7. func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls.
  8. title_page("SAVE FORMATS", "Read an older or damaged scrapbook", "Check the data shape before trying to show any stamp.")Calls title_page with the values in its parentheses.
  9. status = label("", Vector2(61, 227), 27, GOLD)Stores the new value in status. The expression calls label with the values in its parentheses.
  10. stamps = label("", Vector2(62, 283), 18, SEA)Stores the new value in stamps. The expression calls label with the values in its parentheses.
  11. version_note = label("", Vector2(62, 316), 16)Stores the new value in version_note. The expression calls label with the values in its parentheses.
  12. place_button("Version 1", Vector2(62, 411), inspect.bind({"format": 1, "earned": true}))Calls place_button with the values in its parentheses.
  13. place_button("Version 2", Vector2(244, 411), inspect.bind({"format": 2, "stamps": ["first_display", "window_crew", "unknown", "window_crew"]}))Calls place_button with the values in its parentheses.
  14. place_button("Damaged file", Vector2(426, 411), inspect.bind({"format": 2, "stamps": "broken"}))Calls place_button with the values in its parentheses.
  15. place_button("Future version", Vector2(608, 411), inspect.bind({"format": 9, "stamps": ["first_display"]}))Calls place_button with the values in its parentheses.
  16. inspect({"format": 1, "earned": true})Calls inspect with the values in its parentheses.
  17. func upgrade(source: Variant) -> Dictionary:Receive a flexible value. Validation decides whether the value belongs to any supported format.
  18. if not source is Dictionary:Stop before accessing dictionary keys on a different kind of object.
  19. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  20. var version: Variant = source.get("format", 0)Creates a variable named version. The expression looks up a named or indexed value, using a fallback when the call gives one. The type after the colon says what kind of value it can hold.
  21. if not version is int:Require an integer version number. A string that looks numeric remains an invalid record here.
  22. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  23. if version == 1:Checks version == 1. The indented instructions below run only if this test passes.
  24. var old_flag: Variant = source.get("earned", false)Read the original earned flag without guessing that it is the correct type until the next check.
  25. if not old_flag is bool:Refuse a malformed version-one flag so an arbitrary value can't earn a stamp.
  26. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  27. return {"format": CURRENT_FORMAT, "stamps": ["first_display"] if old_flag else []}Preserve the legacy earned stamp in the newer list format. The source is never overwritten.
  28. if version != CURRENT_FORMAT or not source.get("stamps") is Array:Refuse a future version or a broken stamp array rather than resetting the record.
  29. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  30. var kept: Array[String] = []Build a fresh list of names so the source remains untouched.
  31. for value in source["stamps"]:Repeats the indented instructions for each value in source["stamps"].
  32. if value is String and value in VALID and value not in kept:Keep a known, correctly typed stamp at most once.
  33. kept.append(value)Adds an item to the end of a list.
  34. return {"format": CURRENT_FORMAT, "stamps": kept}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  35. func inspect(source: Variant) -> void:Defines inspect, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  36. var result := upgrade(source)Creates a variable named result. The expression calls upgrade with the values in its parentheses. Godot infers the type from the first value.
  37. status.text = "SCRAPBOOK READY" if not result.is_empty() else "RECORD NEEDS ATTENTION"Updates status.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  38. stamps.text = "Stamps · " + ", ".join(result["stamps"]) if not result.is_empty() else "No badge updates applied."Updates stamps.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  39. version_note.text = "Read into format %d" % result["format"] if not result.is_empty() else "The original record is unchanged."Explain how the lab handled the record, including whether it was left untouched.
  40. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  41. backdrop()Calls backdrop with the values in its parentheses.
  42. panel(Rect2(45, 170, 860, 192), Color("#244457"), GOLD)Calls panel with the values in its parentheses.
  43. const PAPER := Color("#fff4de")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  44. const GOLD := Color("#f5bd79")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value.
  45. const SEA := Color("#9ddcd0")Creates a constant named SEA. The expression builds a colour from these values. Godot infers the type from the first value.
  46. const INK := Color("#172c3c")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  47. const EDGE := Color("#54817f")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value.
  48. func title_page(unit: String, heading: String, subtitle: String) -> void:Defines title page, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  49. label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)Make a small line above the main heading so you can tell which checkpoint is open.
  50. label(heading, Vector2(44, 65), 33)Calls label with the values in its parentheses.
  51. label(subtitle, Vector2(46, 119), 16, SEA)Calls label with the values in its parentheses.
  52. func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  53. var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value.
  54. item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words.
  55. item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at.
  56. item.add_theme_font_size_override("font_size", pixels)This Label has its own readable type size. Changing that value leaves the other labels alone.
  57. item.add_theme_color_override("font_color", ink)This label keeps the chosen text ink even when the default theme changes.
  58. add_child(item)Adds the new node to the scene tree so that Godot can run and draw it.
  59. return itemFinishes the function and hands its result back to the caller. The expression reads item.
  60. func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:Defines place button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  61. var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value.
  62. control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words.
  63. control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at.
  64. control.custom_minimum_size = Vector2(width, 48)Give the button room for its label and an easy target for taps. Containers and layouts can allocate more space.
  65. control.add_theme_font_size_override("font_size", 17)Calls control.add_theme_font_size_override with the values in its parentheses.
  66. control.add_theme_color_override("font_color", PAPER)Calls control.add_theme_color_override with the values in its parentheses.
  67. control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))Calls control.add_theme_stylebox_override with the values in its parentheses.
  68. control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  69. control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  70. control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))Draw a gold outline around keyboard focus. Other button styles can still indicate hover and press independently.
  71. control.pressed.connect(action)pressed fires on a successful control activation. Godot calls the function passed in without running it at setup time.
  72. add_child(control)Adds the new node to the scene tree so that Godot can run and draw it.
  73. return controlFinishes the function and hands its result back to the caller. The expression reads control.
  74. func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:Defines style, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  75. var block := StyleBoxFlat.new()Creates a variable named block. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value.
  76. block.bg_color = fillStores the new value in block.bg_color. The expression reads fill.
  77. block.border_color = edgeStores the new value in block.border_color. The expression reads edge.
  78. block.set_border_width_all(line)Apply one border line width to all four edges of the card.
  79. block.set_corner_radius_all(8)Round each corner of this reusable style by eight pixels.
  80. return blockFinishes the function and hands its result back to the caller. The expression reads block.
  81. func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:Defines panel, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  82. draw_style_box(style(fill, edge), rect)Calls draw_style_box with the values in its parentheses.
  83. func backdrop() -> void:Defines backdrop, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  84. draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))Paints a rectangle at the given position and size.
  85. panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))Subtract space on both sides of the canvas. As the window changes, the outer frame fits within it.
  86. func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:Defines paint words, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  87. draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)Godot draws the words from the baseline at the supplied pixel position using its fallback typeface.

Find and fix a bug

If you accidentally replace version 9 with an empty record, separate the return for an unrecognised format from success and keep that original save.

Try a change

Add a test fixture with a string version, an empty valid list and a duplicate known stamp. Explain the three different outcomes.