Skip to content

Instantly share code, notes, and snippets.

@Sarctiann
Last active May 11, 2024 01:56
Show Gist options
  • Save Sarctiann/ad13fa59fd35d6e34e8925c088bbbc1c to your computer and use it in GitHub Desktop.
Save Sarctiann/ad13fa59fd35d6e34e8925c088bbbc1c to your computer and use it in GitHub Desktop.
-- remember, doc comments starts with --- (three dashes).
local a = collectgarbage("count") * 1024
--- Docs for SuperClass (this is a Metatable)
local SuperClass = {
__tostring = function()
return "SuperClass.__tostring method."
end,
}
function SuperClass.new()
--- Docs for SuperClass
--- @class SuperClass
local self = {
--- Docs for inherited_method
inherited_method = function()
return "this is an inherited method"
end,
}
return setmetatable(self, SuperClass)
end
-----------------------------------------------------------------------------------------------
--- Docs for Class (this is a Metatable)
local Class = {
__tostring = function()
return "Class.__tostring method"
end,
}
-- "static" method should be defined in the Class table.
function Class.new()
-- private attrs should be defined here (function local scope)
local private = "this is a private attr"
--- Docs for the instance
--- @class Class : SuperClass
local self = SuperClass.new()
--- Docs for public_field
self.public_field = "this is a public attr"
--- Docs for get_private
function self.get_private()
return private
end
-- Here is where the magic happens:
-- With this line, the class will inherit the SuperClass metamethods
-- and Class will have the Class meta.
return setmetatable(self, setmetatable(Class, SuperClass))
end
----------------------------------------- Here a Demo -----------------------------------------
local i = Class.new()
print(Class)
-- This would print `nil`. but it is commented because it also produces an LS warning
-- print(i.private_field)
print(i)
print(i.public_field)
print(i.get_private())
print(i.inherited_method())
local b = collectgarbage("count") * 1024
print("\nBytes before instantiation: " .. a .. " Bytes")
print("Bytes after instantiation: " .. b .. " Bytes")
print("Estimated Bytes running: " .. b - a .. " Bytes")
-----------------------------------------------------------------------------------------------
-- Making the Class table local, you need to import it where you want to use it:
-- local Class = require("this_file")
-- local i = Class.new()
-- Alternatively, you can make it global, so you can use it just requiring the file (is not recommended):
-- require("this_file")
-- local i = Class.new()
return Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment