Singleton: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
(Removed unnecessary padding.) |
||
(5 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
__NOTOC__ | |||
{{Useful Class}} | {{Useful Class}} | ||
This class allows you to restrict the instantiation of a specific class to one object. | This class allows you to restrict the instantiation of a specific class to one object. | ||
Line 7: | Line 6: | ||
sbx320's classLib, can be found Here[https://github.com/sbx320/lua_utils/blob/master/classlib.lua] | sbx320's classLib, can be found Here[https://github.com/sbx320/lua_utils/blob/master/classlib.lua] | ||
OOP on | |||
==Code== | ==Code== | ||
Line 37: | Line 38: | ||
end | end | ||
</syntaxhighlight> | </syntaxhighlight> | ||
'''Call class methods by newest instance''' | '''Call class methods by newest instance''' | ||
== | ==Example== | ||
<syntaxhighlight lang="lua"> | <syntaxhighlight lang="lua"> | ||
-- DEFINE CLASS | -- DEFINE CLASS | ||
TestClass = inherit(Singleton) | |||
function | function TestClass:run() | ||
-- DO SOMETHING | -- DO SOMETHING | ||
end | end | ||
TestClass:getSingleton():run() | |||
</syntaxhighlight> | </syntaxhighlight> | ||
==See Also== | ==See Also== | ||
{{Useful_Classes}} | {{Useful_Classes}} |
Latest revision as of 12:52, 14 February 2024
This class allows you to restrict the instantiation of a specific class to one object.
Requirements
sbx320's classLib, can be found Here[1]
OOP on
Code
Singleton = {} function Singleton:getSingleton(...) if not self.ms_Instance then self.ms_Instance = self:new(...) end return self.ms_Instance end function Singleton:new(...) self.new = function() end local inst = new(self, ...) self.ms_Instance = inst return inst end function Singleton:isInstantiated() return self.ms_Instance ~= nil end function Singleton:virtual_destructor() for k, v in pairs(super(self)) do v.ms_Instance = nil v.new = Singleton.new end end
Call class methods by newest instance
Example
-- DEFINE CLASS TestClass = inherit(Singleton) function TestClass:run() -- DO SOMETHING end TestClass:getSingleton():run()
See Also
- Singleton » This class allows to restrict the instantiation of a specific class to one object.
- CThread » This class represents a simple coroutine manager which can be used to limit method calls / loop.
- Importer » This class make easy to use exported functions.
- Observable » Observable variables. Call function on variable value change.
- MatrixPOP » This class allows to use simple matrix without using MTA's OOP functions