Hello. I am trying to access a json file here which will store the highscores for my game. This bit of code here is so I can access the file and I will make it so the high score is displayed on the title screen.
local json = require("json")
local function loadHighscore(filename)
local content = sys.load(filename)
if content == nil then
print("Failed to load JSON content from file: " .. filename)
return nil
end
local success, data = pcall(json.decode, content)
if not success or not data or not data.numbers then
print("Invalid or missing data in JSON file: " .. filename)
return nil
end
table.sort(data.numbers, function(a, b) return a > b end)
--Return the highest score (first value)
return data.numbers[1]
end
function init(self)
self.file_path = sys.get_save_file("main", "test.json")
local highscore = loadHighscore(self.file_path)
end
I have accessed the json file using the same method in another script to sort the data however when this script runs it crashes. This is what the console reads:
I have changed the script so it is not decoding but it is still crashing unfortunately
local function loadHighscore(filename)
local content = sys.load(filename)
if content == nil then
print("Failed to load JSON content from file: " .. filename)
return nil
end
local data = content
if not data or not data.numbers then
print("Invalid or missing data in JSON file: " .. filename)
return nil
end
table.sort(data.numbers, function(a, b) return a > b end)
-- Return the highest score (first value)
return data.numbers[1]
end
function init(self)
self.file_path = sys.get_save_file("main", "test.json")
local highscore = loadHighscore(self.file_path)
end
Not sure if this exactly what you meant but here is code where stuff is written to the file.
local function writeJSONToFile(file_path, data)
local file = io.open(file_path, "w")
if not file then
print("Failed to open JSON file for writing")
return
end
file:write(json.encode(data))
file:close()
end
Generally, the sys.save() will save a lua table to file and sys.load() will load that file to a lua table. You don’t need to encode or decode your data
local function saveDataToFile(file_path, data)
local success = sys.save(file_path, data)
if not success then
print("Failed to save data to file: " .. file_path)
end
end
You can go to the saved file location to check. I think your old file is still there. If yes, delete it and try again. Also make sure the file path is correct