8000 Enhancement: Access to (meta)methods for Vector2 and Vector3 types · Issue #32 · TSnake41/raylib-lua · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
HDPLocust opened this issue May 1, 2025 · 0 comments
Open

Comments

@HDPLocust
Copy link
HDPLocust commented May 1, 2025

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 HDPLocust changed the title Add default __index field for Vector2 and Vector3 types Enhancement: Access to (meta)methods for Vector2 and Vector3 types May 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0