Skip to reading
Lua Scripting

Edit text files and JSON

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page

LESSON 11

Keep a small journal and update a preference without erasing the other keys.

Code example
local Script = {}
Code example
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
end
Code example
return Script

Run 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.

Page 29 of 133Permalink
Go to page