You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Lua Vector3类中__add运算符无法正常工作的问题排查

Lua中Vector3类正确添加__add元方法的方式

你的错误核心在于两点:

  1. 多余定义了空的function Vector3(x,y,z) end,后续虽将Vector3覆盖为表,但__add方法中错误地尝试直接调用Vector3表来创建实例(Lua中表无法直接调用,需通过构造函数Vector3.new)。
  2. __add元方法内未使用正确的实例创建方式。

基于你提供的原始Vector3脚本,正确的修改方式如下:

#Vector3.lua
Vector3 = {}
Vector3.__index = Vector3

-- 添加__add元方法实现向量相加
Vector3.__add = function(a, b)
    return Vector3.new(
        a.x + b.x,
        a.y + b.y,
        a.z + b.z
    )
end

function Vector3.new(x,y,z)
  local instance = 
  {
    x = x or 0,
    y = y or 0,
    z = z or 0
  }
  setmetatable(instance, Vector3)
  return instance
end

function Vector3:printX()
  return self.x
end

你的main.lua无需修改,运行后会输出6(即1+5的结果),符合向量相加的预期。

内容的提问来源于stack exchange,提问作者TheJalfireKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:07:49