raylib-lua icon indicating copy to clipboard operation
raylib-lua copied to clipboard

Enhancement: Access to (meta)methods for Vector2 and Vector3 types

Open HDPLocust opened this issue 8 months ago • 0 comments

ffi.metatype assigns to all ffi-types one single global ffi-metatable (that is used for any metatype object):

local vec2 = rl.new("Vector2")

local Vector2_mt = getmetatable(vec2) 
--> "ffi"

local Vector2_mt = debug.getmetatable(vec2) 
local Vector3_mt = debug.getmetatable(rl.new("Vector3")) 

-- this is single global metatable for every metatype object that calls selects metamethod dependent on object type.
print(Vector2_mt == Vector3_mt) --> true

So, we can't safely add something even with debug.getmetatable.

Possible fix. /compat.lua:

local Vector2_mt = {
  __add = function(...) ... end,
  ...
}

-- add this little thing
Vector2_mt.__index = Vector2_mt -- looping but okay
ffi.metatype("Vector2", Vector2_mt)

Now we can take any Vector2, get it's index and fill it with new methods (or even metamethods):

local Vec2 = rl.new("Vector2")
local Vector2_mt = Vec2.__index

Vector2_mt.Negate= rl.Vector2Negate

Vector2_mt.__pow = function(self, n)
  return rl.new("Vector2", self.x^n, self.y^n)
end

-- Can be used everywhere
local OtherVec2 = rl.new("Vector2", 10, 20)
print(OtherVec2:Negate()) --> Vector2 (-100 -200)
print(OtherVec2^2) --> Vector2 (100 400)

HDPLocust avatar May 01 '25 19:05 HDPLocust