Initial commit: the FS25 Lua mod (live.json data export), the FS25-WebDashboard project (Node/web dashboard + PySide6 desktop variant), and FarmHUD (standalone PySide6 companion app with Discord Rich Presence, settings, and installer).
109 lines
2.6 KiB
Lua
109 lines
2.6 KiB
Lua
--[[
|
|
Json.lua - minimal, dependency-free JSON encoder for FS25_FarmHUD.
|
|
|
|
Farming Simulator's Lua sandbox does not ship a JSON library, so we bring our
|
|
own tiny encoder. Only encoding is needed (the mod never reads JSON back),
|
|
so this intentionally does not implement a decoder.
|
|
|
|
Usage:
|
|
local text = Json.encode({ foo = "bar", list = {1, 2, 3} })
|
|
]]
|
|
|
|
Json = {}
|
|
|
|
local ESCAPES = {
|
|
["\\"] = "\\\\",
|
|
["\""] = "\\\"",
|
|
["\n"] = "\\n",
|
|
["\r"] = "\\r",
|
|
["\t"] = "\\t",
|
|
}
|
|
|
|
local function encodeString(s)
|
|
s = tostring(s)
|
|
s = s:gsub('[\\"\n\r\t]', ESCAPES)
|
|
-- strip any other control characters that would produce invalid JSON
|
|
s = s:gsub("[\1-\31]", "")
|
|
return '"' .. s .. '"'
|
|
end
|
|
|
|
local function isArray(t)
|
|
local count = 0
|
|
for _ in pairs(t) do
|
|
count = count + 1
|
|
end
|
|
if count == 0 then
|
|
return true -- treat empty tables as empty arrays ([]) rather than {}
|
|
end
|
|
for i = 1, count do
|
|
if t[i] == nil then
|
|
return false
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
|
|
local encodeValue
|
|
|
|
local function encodeArray(t, out)
|
|
out[#out + 1] = "["
|
|
local n = #t
|
|
for i = 1, n do
|
|
if i > 1 then
|
|
out[#out + 1] = ","
|
|
end
|
|
encodeValue(t[i], out)
|
|
end
|
|
out[#out + 1] = "]"
|
|
end
|
|
|
|
local function encodeObject(t, out)
|
|
out[#out + 1] = "{"
|
|
local first = true
|
|
for k, v in pairs(t) do
|
|
if not first then
|
|
out[#out + 1] = ","
|
|
end
|
|
first = false
|
|
out[#out + 1] = encodeString(k)
|
|
out[#out + 1] = ":"
|
|
encodeValue(v, out)
|
|
end
|
|
out[#out + 1] = "}"
|
|
end
|
|
|
|
encodeValue = function(v, out)
|
|
local t = type(v)
|
|
if v == nil then
|
|
out[#out + 1] = "null"
|
|
elseif t == "string" then
|
|
out[#out + 1] = encodeString(v)
|
|
elseif t == "number" then
|
|
if v ~= v or v == math.huge or v == -math.huge then
|
|
out[#out + 1] = "null" -- NaN / Infinity are not valid JSON
|
|
else
|
|
out[#out + 1] = tostring(v)
|
|
end
|
|
elseif t == "boolean" then
|
|
out[#out + 1] = v and "true" or "false"
|
|
elseif t == "table" then
|
|
if isArray(v) then
|
|
encodeArray(v, out)
|
|
else
|
|
encodeObject(v, out)
|
|
end
|
|
else
|
|
-- functions, userdata, threads: not representable, encode as null
|
|
out[#out + 1] = "null"
|
|
end
|
|
end
|
|
|
|
---Encode a Lua value (typically a table) as a JSON string.
|
|
---@param value any
|
|
---@return string
|
|
function Json.encode(value)
|
|
local out = {}
|
|
encodeValue(value, out)
|
|
return table.concat(out)
|
|
end
|