I want to be able to have 'objects' with certain functions that refer to themselves (I have no idea what to call this) in Lua. I have seen code of what I'm trying to do but I have never understood what any of it actually means. I have tried looking over the Lua website but no luck.
Basic Code:
table = {}
function newTable(...)
...
return setmetatable(table)
end
function table:funcName(...)
...
end
Can someone explain what is going on here and how I can use this please? Thanks for reading!
missingno already mentioned one resource that explains how this works. You can also check out lua wiki's OOP section for more explanation and examples.
To summary briefly your example, starting with how to use it. Note, I changed some of the names so it doesn't affect the standard modules that comes with lua. You create a new object by calling
newObject
. You can invoke that object's methods using:
followed by the method name:You'll need to know a bit about metatables to understand how this machinery works behind the scenes. When you perform a call like:
That is just syntax sugar for:
This can be broken down further into:
Now
object1
is just an empty table returned bynewObject
-- it doesn't have a"my_function"
key. Normally this would result in an error because you're trying to call anil
value. However, you can change this behavior using metatables. The basic idea is to setup the__index
metamethod to point to a table that holds your class methods:The method lookup process will then look like this:
object1
->table
. Ifobject1
doesn't have a key,table
is consulted next. Iftable
has that key the associated value is returned. Iftable
doesn't have it either thennil
is returned sincetable
doesn't have a metatable.With this setup you can "override" a method for a particular object instance by just assigning the method name and function as key-value pair for that object.