Hello. I have never seen tutorial about metamethods, or how to use it in practice.
Ofcourse if you are more familiar with scripting you can easily read tutorials over internet.
But still I think that using metamethods is something extremely usefull.
So what metamethod is? Its an action made on table. There are few kinds of metamethods, in this tutorial I will use __add metamethod.
But I won't give you a theory, you can read about it in inthernet, lets make some practice.
This is some sample code:
I hope that obvious is result of action
It will give us error in console.
But yet this is possible to add 2 arrays using .add methamethod!
So basicly when we use code like that, it will allow to add arrays that contains indexes x,y,z. If array wont have them (or one of them) it will return error.
Now lets try this.
Result of print should be : 42, 86, 9
Conculsion:
Key to everything is setmetatable function. It allows us to make wierd nice things with regular lua tables. I don't know if given examples won't give any errors when you want test it in your engine, but I think that you can easily fix it if you are a litlle skilled in lua.
Ofcourse if you are more familiar with scripting you can easily read tutorials over internet.
But still I think that using metamethods is something extremely usefull.
So what metamethod is? Its an action made on table. There are few kinds of metamethods, in this tutorial I will use __add metamethod.
But I won't give you a theory, you can read about it in inthernet, lets make some practice.
This is some sample code:
Code:
local position = getPlayerPosition(cid)
local position2 = {x = 123, y =455, z= 7}
I hope that obvious is result of action
Code:
local summary = position + position2
It will give us error in console.
But yet this is possible to add 2 arrays using .add methamethod!
Code:
local mt = {} --metatable that will hold our metametods.
mt.__add = function(a,b) --We tell what to do when arithmetical operation occours
return setmetatable({x = a.x + b.x, y= a.y+b.y,z = a.z+b.z},mt) --it will return new position, with metatable attached.
end
function Position:new(x,y,z)
local obj = {x = x, y=y,z=z }
return setmetatable(obj,mt)
end
So basicly when we use code like that, it will allow to add arrays that contains indexes x,y,z. If array wont have them (or one of them) it will return error.
Now lets try this.
Code:
local pos1 = Position:new(30,30,8)
local pos2 = Position:new(12,56,1)
local pos3 = pos1 + pos2
print(pos3.x,pos3.y,pos3.z)
Conculsion:
Key to everything is setmetatable function. It allows us to make wierd nice things with regular lua tables. I don't know if given examples won't give any errors when you want test it in your engine, but I think that you can easily fix it if you are a litlle skilled in lua.
Last edited: