Saving Tables using LUA without JSON

The most frequently asked question is how to save data to files. There was the PropertyBag library created by me, then there was a JSON option that could help save tables and nested tables. This article is a quick way to use a non JSON technique.

Using JSON is a preferred manner to save nested data, the reason being simple that the JSON libraries have two functions, encode and decode these take a table and return a JSON string or return a Lua table when passed a JSON encoded string. So the amount of work involved is minimal as most of the work is done by those two functions mentioned earlier.

First let us look at how the JSON method works

JSON = require("json")

local test = 
  {
    name = "Lua",
    frameworks = 
    {
     "LOVE",
     "Codea",
     "Moai",
    },
  }

local jStr = JSON.encode(test)
print("Json string", jStr)

local jTbl = JSON.decode(jStr)
print(type(jTbl))

So you can see how this works.

So what is the wonderful non JSON method and why would one want to use a non JSON method? For starters, most frameworks do not come with a JSON library inbuilt, so it is expected to be included, which in itself can lead to other problems.

This method relies on the fact that Lua can read and execute Lua code. We shall use this functionality to read data back into Lua. There are two functions in Lua that can offer us this functionality, they are loadstring and loadfile and heres a way to see how it works.

local resfile = load("somefile.lua")
 resfile()

this shall run and execute the code in the file called somefile.lua. The other method is using loadstring as

local thiscode = "print('Hello from loadstring')"
 local rescode = loadstring(thiscode)
 rescode()  -- this shall execute the code in the string thiscode

Now how would this be useful to us with loading tables?

One very important thing to note is that these two functions are available in any Lua based framework unless it is sandboxed. So, the framework that does not have this functionality is definitely CoronaSDK. So when we would want to load a table from a saved file, the way could be as simple as

local resfile = load("saveddata.lua")
 resfile()

and the savedata.lua would be something like

theTbl = 
  {
    name = "Lua",
    frameworks = 
    {
     "LOVE",
     "Codea",
     "Moai",
    },
  }

and we can use the table that is now referenced in the variable theTbl like

for i, j in pairs(theTbl) do
  print(i,j)
 end

and the output is

name Lua
frameworks table: 0x1230d0


For saving the same into a Lua file, we need to write the table back to the file, here's some code to do the same, http://www.lua.org/pil/12.1.1.html or from https://github.com/VADemon/Save-table-to-file-Lua/blob/master/save_to_table-alpha.lua

Comments

Popular Posts