我正在處理一種管理2D矢量的方法,到目前爲止它的工作進展順利。我有一個模塊文件,我打電話給Positions.lua,其中包含Vector2.new(X,Y)的信息。在Lua中使用Metamethods:使用_add時出錯
我從來沒有真正使用Metamethods,所以它一直是一種學習體驗。我想要輕鬆地將兩個Vector2加在一起。這是我的Metamethod功能:
local vectorMethods = {
_add = function(lhs,rhs)
return Positions.Vector2.new(lhs.x+rhs.x,lhs.y+rhs.y);
end
};
我已經創建了這個閱讀關於metamethods的Lua用戶wiki頁面。基於我所看到的,如果我使用setmetamethod將我的Vector2錶鏈接到metamethod,這應該可以工作。
Positions = require("Positions");
X = Positions.Vector2.new(154.1,353.3);
Y = Positions.Vector2.new(5,5);
s,m = pcall(function() J = X+Y end);
if not s then
print("Failed due to error: "..m);
end
這是輸出我收到:
Failed due to error: main.lua:12: attempt to perform arithmetic on global 'X' (a table value)
什麼我可以做錯了任何想法?我很抱歉沒有顯示整個代碼,我覺得發佈太多了。
對不起,這篇文章組織得不好。我不會在論壇上發帖。
謝謝你給我的任何幫助!
我發現使用 J =(getmetatable(X)._ add(X,Y)) 工作,這意味着metamethod本身正在工作。 –