Skip to content

Instantly share code, notes, and snippets.

@Sarctiann
Last active May 11, 2024 01:56
Show Gist options
  • Save Sarctiann/1a58d731635240722ed93f2b033d6749 to your computer and use it in GitHub Desktop.
Save Sarctiann/1a58d731635240722ed93f2b033d6749 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,
}
--- Docs for SuperClass
--- @class SuperClass
local super_class = {}
--- Docs for inherited_method
super_class.inherited_method = function()
return "this is an inherited method"
end
setmetatable(super_class, SuperClass)
-----------------------------------------------------------------------------------------------
--- Docs for Class (this is a Metatable)
local Class = {
__tostring = function()
return "Class.__tostring method"
end,
}
-- private attrs should be defined here (function local scope)
local private = "this is a private attr"
--- Docs for get_private
local function get_private()
return private
end
--- Docs for the instance
--- @class Class : SuperClass
local class = super_class
--- Docs for public_field
class.public_field = "this is a public attr"
class.get_private = get_private
setmetatable(class, setmetatable(Class, SuperClass))
----------------------------------------- Here a Demo -----------------------------------------
local i = class
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