Edit text files and JSON
LESSON 11
Keep a small journal and update a preference without erasing the other keys.
local Script = {}function Script.run(context)
local path = "user://archive_workshop/journal.txt"
local old = tostring(ReadTextFile(path, ""))
local line = DateTimeString(true) .. " Inspected the dial.\n"
if not WriteTextFile(path, old .. line) then
return "Could not write journal."
end
local prefs = "user://archive_workshop/preferences.json"
local data = ReadJSONFile(prefs, { hints = true })
data.hints = false
if not WriteJSONFile(prefs, data) then
return "Could not write preferences."
end
return ReadJSONFile(prefs).hints
endreturn ScriptRun twice. The journal gains a second line and the preference remains false. WriteTextFile replaces
the file and creates missing parent directories beneath user://. Reading before rewriting implements
append for a small, single-writer journal. For large logs use a streaming file API. These sample paths
are dedicated to the workshop.
ReadTextFile supplies its fallback when the file cannot be opened. ReadJSONFile uses its fallback for
empty or unparseable JSON. If a file can contain valid JSON of the wrong shape, validate that it is a
dictionary before changing fields. WriteJSONFile returns success or failure. Keep a save-slot action
for a complete game snapshot.
Lua also opens standard libraries in this build. io.open uses operating-system paths. The PCA helpers
understand Godot's user:// path on each export platform.
