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
Then just to run a test I took a string variable and tested the type
Then i called createBasicMetatable() to return the metatable and store it in var and tested the type again
So i wanted to see how this could be useful, so i gave var a property and gave it a value
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
Then to test everything i called the var's metamethod, var's property and checked its type
I think this just might be an easier way for people to generate metatables
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: