Corona SDK Utilities: NewVariable function

Hello Corona Devs,

Second function I want to share with you is UTL.NewVariable. It is committed into GitHub repository and is located in file utl/settings.lua

Please feel free to use/share them. If you find any bugs or have any comments please don’t hesitate to write me.



function UTL.NewVariable(filename, default)
	local tbl = UTL.LoadTable(filename);
	if not (tbl) then
		tbl = default;
		UTL.SaveTable(tbl, filename);

	return setmetatable({
			Get = function()
				return tbl;
		}, {
		__index = function(t, key)
			return tbl[key];

		__newindex = function(t, key, value)
			tbl[key] = value;
			UTL.SaveTable(tbl, filename);

This function uses UTL.LoadTable and UTL.SaveTable function you can find below:

function UTL.SaveTable(t, filename)
	local path = system.pathForFile( filename, system.DocumentsDirectory)
	local file =, "w")
	if file then
		local contents = JSON.encode(t)
		file:write( contents )
		io.close( file )
		return true
		return false

function UTL.LoadTable(filename, dir)
	if (dir == nil) then
		dir = system.DocumentsDirectory;

	local path = system.pathForFile( filename, dir)
	local contents = ""
	local myTable = {}
	local file = 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 
	return nil


What it does

Function NewVariable creates table to which you can set/get values and every time value in that table is changed it will be saved in file specified. Initial value of variable will be one that is saved in file.


Here is a small example:

local var = UTL.NewVariable("test.json", {
    counter = 0
var.value1 = "something";
var.value2 = 12;
var.counter = var.counter + 1;

print("value1 = ", var.value1);
print("value2 = ", var.value2);
print("counter = ", var.counter);

Above example will output following:

First run:
value1 = 	something
value2 = 	12
counter = 	1

Second run:
value1 = 	something
value2 = 	12
counter = 	2

Third run:
value1 = 	something
value2 = 	12
counter = 	3


When to use

This object is useful when you want to save apps state and restore on next run easily.

For example:

local Settings = UTL.NewVariable("settings.json", {
    soundEnabled = true,
    musicEnabled = true,
    coins = 0


store:addEventListener("purchase", function(amount)
    Settings.coins = Settings.coins + amount;


Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *