Skip to reading
PCA Script Programming

18. JSON and safe file editing

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
Code example
function run()
    let path = "user://tutorial/preferences.json"
    let prefs = read_json_file(path, {"music": 0.7})
    prefs["music"] = 0.5
    let saved = write_json_file(path, prefs, "  ")
    if not saved
        warn("Preferences could not be saved.")
    end
    return saved
end

user:// is the game’s writable user-data area. It is a logical path, so you do not need a Windows drive letter or a Linux home path. The write helpers create parent directories and overwrite the complete target file. They do not open an interactive file editor.

To edit text, read it with read_text_file(), change the string, then write the complete new string with write_text_file(). There is no append mode, line insertion, rename or delete builtin. Read/write JSON helpers suit settings, custom notes or exported progress; use the save-game actions for a full game save.

Code example
function run()
    let path = "user://tutorial/notes.txt"
    let old = read_text_file(path, "")
    return write_text_file(path, old + "Visited the archive.\n")
end

Writing is restricted to user:// paths. Read helpers can also read packaged resources when a valid resource path is available, but your source project’s absolute paths are not portable. Always check the returned Boolean before telling the player that a file was saved.

Page 25 of 357Permalink
Go to page