【问题标题】:(Lua) Doing mathematical operations with non-number values(Lua) 用非数值做数学运算
【发布时间】:2013-03-17 02:50:42
【问题描述】:

我想为 Lua 制作某种 Vector3 库,它可以让您使用简单的语法进行简单的 3D 位置操作。我会提到我正在使用 Luaj 来运行 Lua 代码以进行 Java 操作。

这是我的开始代码:

Vector3 = {
new = function (x1, y1, z1)
  return {x = x1, y = y1, z = z1}
end
}



Position1 = Vector3.new(1, 5, 8)
Position2 = Vector3.new(4, 7, 2)

这就是我希望能够发生的事情:

Subtraction = Position1 - Position2
print(Subtraction.x, Subtraction.y, Subtraction.z) -- prints "-3, -2, 6"

关于使 EXACT 代码正常工作的任何想法?

【问题讨论】:

  • 你应该定义 __sub 元方法。
  • 谢谢!这绝对是我的问题的解决方案!

标签: lua


【解决方案1】:

这就是元表和元方法的用途。您应该阅读in the documentation

基本上,它们可以让您重新定义运算符(以及其他一些事情)对您的值执行的操作。您现在想要的是定义__sub 元方法,它定义了如何处理- 运算符。我想将来你也会想重新定义其他元方法。

首先,在您的Vector3“类”中定义一个减法函数,该函数接受两个向量:

function Vector3.subtract(u,v)
    return Vector3.new(u.x - v.x, u.y - v.y, u.z - v.z)
end

然后创建让Vector3 知道它应该给所有向量的元表:

Vector3.mt = {__sub = Vector3.subtract}

当你创建一个新的向量时:

new = function (x1, y1, z1)
    local vec = {x = x1, y = y1, z = z1}
    setmetatable(vec, Vector3.mt)
    return vec
end

您还可以将元表 (mt) 设为您的 new 函数内的局部变量 - 这将防止外部代码与元表混淆(因为它只能由您的 new 函数访问)。但是,将它包含在 Vector3 中可以让您检查 v - "string" 之类的用法:

function Vector3.subtract(u,v)
    if getmetatable(u) ~= Vector3.mt or
       getmetatable(v) ~= Vector3.mt then
        error("Only vectors can be subtracted from vectors", 2)
    end
    return Vector3.new(u.x - v.x, u.y - v.y, u.z - v.z)
end

【讨论】:

    【解决方案2】:

    你可以这样做:

    Vector3 = {}
    
    mt = {}
    
    function Vector3:new(_x, _y, _z)
      return setmetatable({
        x = _x or 0, 
        y = _y or 0,
        z = _z or 0
      }, mt)
    end
    
    mt.__sub = function(v1, v2) return Vector3:new(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z) end
    mt.__tostring = function(v) return "Vector3=(" .. v.x .. "," .. v.y .. "," .. v.z .. ")" end
    mt.__index = Vector3 -- redirect queries to the Vector3 table
    
    -- test Vector3
    Position1 = Vector3:new(1, 5, 8)
    Position2 = Vector3:new(4, 7, 2)
    Sub = Position1 - Position2
    print(Sub)
    

    将打印:

    Vector3=(-3,-2,6)

    有关 Lua 和 OO 的更多信息,请参阅:http://lua-users.org/wiki/ObjectOrientationTutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2015-04-09
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多