Hello, I was wondering if there really is a way to use the Singleton method using tables. I'm not sure if it's possible, because Lua doesn't have static variables. And if you were to do a require("MySingletonFile") wouldn't it always return a new instance? Or do tables have the same instance no matter what requires them? Hope that was clear enough..
Singleton Oop Question
Mar 24 2013 05:53 AM
Best Answer dmccuskey , 24 March 2013 - 11:20 AM
this is the way i do it inside of my OO modules:
-- at beginning of module local autostore_singleton = nil -- at end of module if autostore_singleton == nil then -- do any setup necessary for your object/table autostore_singleton = AutoStore:new() autostore_singleton:init() autostore_singleton:load() end return autostore_singleton
this works because the code inside of a module is run only once on the first require() even though there might be several of them inside of an app. the module loader simply saves the module return value and uses that for any subsequent module require().
so, what @thomas6 suggests will work for simple tables because of this fact. however, if you are using OO with an object constructor (e.g., new() ), then you will have to do something similar to what i suggest.
ps, the example was taken from my library module dmc_autostore if you want to check out the entire code file: https://developer.coronalabs.com/code/dmc-lib-auto-store .