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

 



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

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

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

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 = 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

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

	local path = system.pathForFile( filename, dir)
	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

 

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.

Example

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;
end);

 

Leave a Reply

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

* Copy This Password *

* Type Or Paste Password Here *