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)”
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:
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 [import]uid: 5833 topic_id: 9415 reply_id: 34448[/import]