• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Metatables in lua

Codex NG

Recurrent Flamer
Joined
Jul 24, 2015
Messages
2,994
Solutions
12
Reaction score
1,657
I was reading up on Metatables in lua it really isn't that hard to understand.

I was thinking if i can return a value from a method or function why can't I do that with a metatable

So I created a function that creates a very basic metatable
Code:
function createBasicMetatable()
    local x = setmetatable({ __index = {} },{
        __call = function(cls, ...)
            return cls.new(...)
        end,
    })
    function x.new()
        local self = setmetatable({}, x)
        return self
    end
    return x
end

Then just to run a test I took a string variable and tested the type
Code:
local var = "this is a string"
print(type(var))
-- string

Then i called createBasicMetatable() to return the metatable and store it in var and tested the type again
Code:
var = createBasicMetatable()
print(type(var))
-- now it prints table

So i wanted to see how this could be useful, so i gave var a property and gave it a value
Code:
var.aprop = 20

I wanted to check if aprop was truely a property of the var metatable
So I created a metamethod for var and used its new property
Code:
    function var:addThis(b)
        return self.aprop + b
    end

Then to test everything i called the var's metamethod, var's property and checked its type
Code:
print(type(var), var:addThis(6), var.aprop)
--output
-- table   26   20

I think this just might be an easier way for people to generate metatables :)
 
Last edited:
To expand upon this the constructor or new metamethod doesn't need to be called within the createBasicMetatable function, this could be defined outside, it really doesn't matter which ever is your preference.

You could very well craft an entire metatable inside the createBasicMetatable function and then call it as needed, this could very well be a template for all your 'objects'

I'll get more into a break down of how a metatable works in comparison to say a php class.
 
Back
Top