64 lines
2.5 KiB
Luau
64 lines
2.5 KiB
Luau
-- examples/data.luau: one record through JSON, YAML, TOML, MessagePack and CBOR; CSV, INI and XML (docs/guide/data.md).
|
|
local F = require("@rosetta")
|
|
local Types = F.Types
|
|
|
|
-- an ordered record with a null, an empty object and a date
|
|
local save = Types.object()
|
|
Types.set(save, "player", "ada")
|
|
Types.set(save, "level", 7)
|
|
Types.set(save, "items", { "sword", "lamp" })
|
|
Types.set(save, "guild", F.data.null)
|
|
Types.set(save, "flags", Types.object()) -- stays {} (a plain {} would be written as [])
|
|
Types.set(save, "saved", Types.Date.parse("2026-10-31T12:00:00Z"))
|
|
|
|
local json = assert(F.saveString(save, { format = "json", indent = 2 }))
|
|
print(json)
|
|
local back = assert(F.data.load(json, { format = "json", ordered = true }))
|
|
assert(back.guild == F.data.null and Types.isObject(back.flags) and back.items[2] == "lamp")
|
|
assert(table.concat(Types.keys(back), ",") == "player,level,items,guild,flags,saved")
|
|
|
|
for _, fmt in { "yaml", "toml", "msgpack", "cbor" } do
|
|
local v = save
|
|
if fmt == "toml" then -- TOML has no null
|
|
v = Types.object()
|
|
for _, k in Types.keys(save) do
|
|
if save[k] ~= F.data.null then
|
|
Types.set(v, k, save[k])
|
|
end
|
|
end
|
|
end
|
|
local bytes = assert(F.save(v, nil, { format = fmt }))
|
|
local again = assert(F.data.load(bytes, { format = fmt }))
|
|
assert(again.player == "ada" and again.level == 7)
|
|
if fmt ~= "yaml" then
|
|
assert(Types.Date.is(again.saved) and Types.Date.toUnix(again.saved) == Types.Date.toUnix(save.saved))
|
|
end
|
|
print(string.format("%-8s %4d bytes", fmt, buffer.len(bytes)))
|
|
end
|
|
|
|
-- CSV: records with a header row
|
|
local csv = "name,score\nada,1200\n\"lee, jr\",400\n"
|
|
local recs = assert(F.data.load(csv, { format = "csv", header = true, numbers = true }))
|
|
local total = 0
|
|
for _, r in recs do
|
|
total += r.score
|
|
end
|
|
print(string.format("csv: %d records, total score %d", #recs, total))
|
|
assert(total == 1600 and recs[2].name == "lee, jr")
|
|
|
|
-- INI with typed values
|
|
local ini = assert(F.data.load("[window]\nwidth = 800\nfullscreen = no\n", { format = "ini", types = true }))
|
|
assert(ini.window.width == 800 and ini.window.fullscreen == false)
|
|
|
|
-- XML: find elements by name
|
|
local doc = assert(F.data.load('<scores><s who="ada">1200</s><s who="bob">950</s></scores>', { format = "xml" }))
|
|
local who = {}
|
|
for _, c in doc.root.children do
|
|
if type(c) == "table" and c.name == "s" then
|
|
table.insert(who, c.attrs.who .. "=" .. c.children[1])
|
|
end
|
|
end
|
|
print("xml: " .. table.concat(who, " "))
|
|
assert(#who == 2)
|
|
print("data example: ok")
|