Singletons in Lua?

Say I want to have a CatManager class that allows me create cats and keep track of them. In other languages I often use singletons for this type of thing. I would like to create a cat like this:

local CatManager = require("CatManager")  
CatManager:createCat("Morris")[/code]  
  
How would I go about creating the CatManager class?   
  
[code]module(..., package.seeall)  
  
function createCat(id)  
 print("creating cat: " .. id)  
end  

Error: “attempt to concatenate local ‘id’ (a table value)”

[import]uid: 52127 topic_id: 9415 reply_id: 309415[/import]

Personally I would create the CatManager class like this:

  
CatManager = {}  
CatManager\_mt = { \_\_index = CatManager }  
  
function CatManager:new()  
  
 local self = {}  
  
 setmetatable( self, CatManager\_mt )  
  
 return self  
  
end  
  
function CatManager:createCat( id )  
 print("creating cat: " .. id)  
end  
  

And then in main.lua would create a global instance of it:

  
require("CatManager")  
  
catManager = CatManager:new()  
  

And then you can create cats from everywhere:

  
catManager:createCat("Morris")  
  

Technically it’s not a singleton class as if you wanted you could create more than one of them however for me it is “good enough”. There are ways to create a more valid singleton class if you want to though. [import]uid: 5833 topic_id: 9415 reply_id: 34438[/import]

I wouldn’t bother with creating a class and then declaring only one instance of that class because that scaffolding would be redundant. In a completely object-oriented language like Java the singleton pattern is useful, but in a language like Lua it seems pointless to me.

Instead I would simply use the module itself as a “singleton.” I mean, you can access it anywhere you put in the require statement, you can declare a bunch of variables in it that only exist one time in that module, and you can access the functions in the module through dot notation:

local CatManager = require("CatManager") CatManager.createCat("Morris") [import]uid: 12108 topic_id: 9415 reply_id: 34441[/import]

That would certainly be the easier/faster/better option :slight_smile: [import]uid: 5833 topic_id: 9415 reply_id: 34443[/import]

Thinking about this is reminding me, I should probably re-architect my code a bit so that all the game settings I currently stick into global variables instead go into a “settings” module. I doubt I will though because my game is about to ship and hey why fix what ain’t broke. [import]uid: 12108 topic_id: 9415 reply_id: 34447[/import]

Yea I’d probably wait till the next project, 11th hour fixes have never really gone down that well for me :slight_smile: [import]uid: 5833 topic_id: 9415 reply_id: 34448[/import]

Thanks, this is helpful. [import]uid: 52127 topic_id: 9415 reply_id: 34451[/import]