Skip to content

Instantly share code, notes, and snippets.

@1bardesign
Created May 12, 2020 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1bardesign/e5887a9ffa8c11f99c3797b9a246f579 to your computer and use it in GitHub Desktop.
Save 1bardesign/e5887a9ffa8c11f99c3797b9a246f579 to your computer and use it in GitHub Desktop.
a heavily commented example of using metatables to implement class-like behaviour in lua
--define the example class table
local example_class = {}
--build the class metatable
--this is instructions to lua for what we want instances to do in certain circumstances
example_class.mt = {
--we only really care about the index metamethod
--this one says that if something is missing in the table this metatable is set on
--to go look in the example_class table
__index = example_class,
}
--build an instance of the example class
function example_class:new()
--build the instance table
--we can include any instance member variables here
--which will be defined per-instance
--rather than per-class
local instance = {
member_variable = "whatever you want",
}
--set the metatable on the instance to the one we defined earlier
setmetatable(instance, self.mt)
--return it
return instance
end
--define some method to use
function example_class:some_method()
print("fantastic!", self.member_variable)
end
--lets create some instances
local a = example_class:new()
local b = example_class:new()
--we'll modify one of them, to show that the data isn't shared
b.member_variable = "changed to something new"
--lets see what they print out when we call the method on each instance
a:some_method() --prints "fantastic whatever you want"
b:some_method() --prints "fantastic changed to something new"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment