Singletons in Lua

Since learning Lua and playing around with Corona and as it is not a very OOP language and is very script based, even more so that javascript, I felt like having a go at trying to see if it was possible to:

  • Structure my projects in a class based way to make them seem more familiar and cleanly organised
  • Mimic some design patterns to find out some of the strength / weaknesses of the language

My first task was structuring the projects I was creating to mimic a more OOP structure, this at first wasn’t easy as most of the examples I could find were very much scripts full of procedural code. Then I stumbled upon Jesse Warden’s Robotlegs for Corona. Written by a fellow actionscripter it was structured in a manner that was very familiar to me and helped a lot in figuring out the best methods for structuring my own code. So after a little playing I decided to see if I could easily create a singleton class in Lua. Now the simplest method of creating a singleton in Lua would be to create a name space with static methods using the ‘:’ operator, which makes your method calls static. This can also be done in actionscript, but multiple instances within a project can still be created if called within different contexts, so the only sure fire way is with the ‘getInstance()’ call. So after a little playing I managed to structure a very simple Lua singleton, which I found to be a lot simpler than I expected:

  1. Singleton = {};
  3. local _instance;
  5. function Singleton.getInstance()
  6.     if not _instance then
  7.         _instance = Singleton;
  8.     end
  10.     --'any new methods would be added to the _instance object like this'
  11.     _instance.getType = function()
  12.         return 'singleton';
  13.     end
  15.     return _instance
  16. end
  18. function Singleton:new()
  19.     print('Singleton cannot be instantiated - use getInstance() instead');
  20. end

Now my only gripe about this class is that the ‘Singleton’ object can still be access globally and altered from outside of the class, but I guess this is just something you have to get used to with dynamic languages. This may not be the best way to do things but during my tests the object created and returned was always the same object, so if you think this is wrong and could be done better please do let me know.

This entry was posted in Games, Lua and tagged , . Bookmark the permalink.

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>