Created
December 15, 2012 05:28
-
-
Save jasonbradley/4291520 to your computer and use it in GitHub Desktop.
Lua read/write data in JSON format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- load the JSON library. | |
local Json = require("json") | |
local JsonStorage = {} | |
-- Function to save a table. Since game settings need to be saved from session to session, we will | |
-- use the Documents Directory | |
JsonStorage.saveTable = function(t, filename) | |
local path = system.pathForFile( filename, system.DocumentsDirectory) | |
local file = io.open(path, "w") | |
if file then | |
local contents = Json.encode(t) | |
file:write( contents ) | |
io.close( file ) | |
return true | |
else | |
return false | |
end | |
end | |
JsonStorage.loadTable = function(filename) | |
local path = system.pathForFile( filename, system.DocumentsDirectory) | |
local contents = "" | |
local myTable = {} | |
local file = io.open( path, "r" ) | |
if file then | |
-- read all contents of file into a string | |
local contents = file:read( "*a" ) | |
myTable = Json.decode(contents); | |
io.close( file ) | |
return myTable | |
end | |
return nil | |
end | |
return JsonStorage |
[31]: myTable = Json.decode(contents);
you added extra colon.
json.decode does not work for me.
local Jsondata = require("jsonstrorage")
local json = require("json")
local unpack = unpack or table.unpack
function LoadData()
data = Jsondata.loadTable("jsonfile")
if data ~= nil then
print("Not nill")
end
print(tostring(json.decode('[1,2,3,{"x":10}]')))
end
LoadData()
I am using this
Wrong code for linux. Using system in local function will always reproduce attempt to index global 'system' (a nil value)
Because it works on Sola2D game framework i guess (which provide a system.* library)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! what library file you use for json.lua? or what luarocks install -json_package- you used? I tried downloading this file https://github.com/rxi/json.lua and also local lfs = require "lfs" with no success. I get attempt to index global 'system' (a nil value)
stack traceback