While developing with Corona SDK I found myself needing (“wanting”) a specific sort of module.
This modules has the following aspects:
- There is always <= 1 instance (0 or 1)
- The instance uses it’s closure to clean-up variables (easier maintenance)
- Auto-complete must be available (so no dynamic require-ing)
- The instance should be destroyable from any other module
I came up with a usable solution which can be seen below:
local t = {} local instance local function destroyInstance() display.remove(instance) instance = nil end function t:getInstance() return instance end function t:createInstance(\_params, \_onShow) instance = display.newGroup() local blablaVar = blabla local blablaRect = display.newRect(instance, 0, 0, 100, 100) transition.to(blablaRect, {x = 1000, delta = true, time = 10000}) blablaRect:addEventListener("finalize", function() transition.cancel(blablaRect) end) function instance:destroy() --extra cleanup here if needed, not needed in this case though destroyInstance() end end return t
Usage would be:
In my worldModule for example:
local worldInterfaceBuilder = require("worldInterfaceBuilder") worldInterfaceBuilder:createInstance({ defaultIcon = "run", color = {1, 0, 0} })
In my playerModule for example:
local worldInterfaceBuilder = require("worldInterfaceBuilder") local worldInterfaceInstance = worldInterfaceBuilder:getInstance() worldInterfaceInstance:doCurrencyAnimation() -- or worldInterfaceInstance:getInstance():doCurrencyAnimation
What do you guys think of this solution, could there be any problems with it? Are there any other available solutions?