Benefits to using a singleton class vs standard module?

I’ve been using OOP with projects more and more lately due to how easy it makes managing growing projects, but every time I create a singleton class I find myself asking if there’s really any benefits to using a class structure over a standard module script for singletons, since in most cases they’re being used as managers for the respective objects. Is there something I’m overlooking?

Singleton:

local Singleton = {}
Singleton.__index = Singleton

function Singleton.new()
	local self = setmetatable({}, Singleton)
	
	self.Class = "Singleton"
	
	return self
end

function Singleton:PrintHello()
	print("Hello")
end

return Singleton.new()

Module:

local Singleton = {}

Singleton.Class = "Singleton"

function Singleton:PrintHello()
    print("Hello")
end

return Singleton

There aren’t any real benefits to the singleton model at least from the Lua perspective. If you don’t need OOP in some cases, it’s ok not to over use it.

Your module approach is also not really a module approach but an OOP+procedural amalgam. If you’re not dealing with objects, you shouldn’t use : at all. This does have a benefit, which is it becomes easier to pass your functions around as free functions without a bound “object.”

1 Like