Skip to reading
BASIC Scripting

Keep settings in a JSON file

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

BASIC IN YOUR GAME

JSON stores named values in a text file. It works well for a preference like “show hints” because the name and value stay together.

Code example
FUNCTION Run()
    DIM path = "user://station/options.json"
    DIM prefs = ReadJSONFile(path, {"hints": TRUE})
    prefs.hints = FALSE
    IF NOT WriteJSONFile(path, prefs) THEN
        RETURN "Write failed"
    END IF
    DIM loaded = ReadJSONFile(path, {})
    RETURN loaded.hints
END FUNCTION

For a missing or unreadable setting, the starting dictionary supplies hints = TRUE. The script changes hints to FALSE and writes the dictionary. It then reads it back. The returned FALSE is the value of hints. The text Write failed is the separate failure result.

A successful JSON parse can still produce the wrong kind of data. This listing expects a dictionary. If another tool or an older edition of your game can write the same file, check the structure and supply defaults for missing fields before using them.

Page 23 of 86Permalink
Go to page