Lua Metatables Using tables as metamethods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Some metamethods don't have to be functions. To most important example for this is the __index metamethod. It can also be a table, which is then used as lookup. This is quite commonly used in the creation of classes in lua. Here, a table (often the metatable itself) is used to hold all the operations (methods) of the class:

local meta = {}
-- set the __index method to the metatable.
-- Note that this can't be done in the constructor!
meta.__index = meta

function create_new(name)
    local self = { name = name }
    setmetatable(self, meta)
    return self
end

-- define a print function, which is stored in the metatable
function meta.print(self)
    print(self.name)
end

local obj = create_new("Hello from object")
obj:print()


Got any Lua Question?