Skip to content

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

@HDPLocust

Description

@HDPLocust

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions