Ok, in hindsight perhaps detailed code posts isn’t ideal for new users especially if they don’t understand local/global and how lua modules work. So here is a cleaned up version that you can use.
Create a file called options.lua and place the following inside:
[lua]module(…, package.seeall)
function set(option, val, scope)
if not scope then scope = “app” end
if not _options then _options = { screen={}, app={} } end
_options[scope][option] = val
end
function get(option, scope)
if _options then
if not scope then scope = “app” end
if _options[scope] then
return _options[scope][option]
else
return nil
end
else return nil
end
end
function clear( scope )
if scope then
_options[scope] = nil
else
_options.app = nil
_options.screen = nil
_options = nil
end
end[/lua]
Inside your main.lua file place this at the top:
[lua]options = require( “options” )[/lua]
Now you can call the option functions from anywhere inside your application:
options.set - Set a variable
options.get - Get a variable
options.clear - Remove the variables
Here are some examples:
To create a screen variable which can be deallocated when you exit the screen:
[lua]options.set( “Colour”, “Red”, “screen” ) – Set a screen variable called Colour to “Red”[/lua]
This variable can be accessed from inside your screen via:
[lua]options.get( “Colour”, “screen” ) – Gets SCREEN variable Colour[/lua]
To create an app variable which will be persistent across your entire app:
[lua]options.set( “Score”, 666, “app” ) – Set an app variable called Score to “666”[/lua]
To retrieve this app variable:
[lua]options.get( “Score”, “app” ) – Gets APP wide variable Score[/lua]
To delete all screen variables which should be done inside the onExit function of whichever director/view/game class you are using:
[lua]options.clear( “screen” ) – Removes all SCREEN variables. Should be called on screenExit[/lua]
To delete all app variables if you want to reset the application:
[lua]options.clear( “app” ) – Removes all APP variables[/lua]
To delete both app and screen applications if you want to reset the application:
[lua]options.clear() – Removes all variables. Can be called if you want to reset the application[/lua]
Remember this isn’t creating some magical local storage for your variables. These variables are all GLOBAL. This method just segments between the variables you want available app wide, and just for a particular screen. You must call options.clear( “screen” ) before you switch to the next screen if you want a clean state. If you don’t call the clear function when you exit the screen the variables will just sit there in memory. [import]uid: 11393 topic_id: 4253 reply_id: 19376[/import]