【问题标题】:Lua - trying to create a good Vec2 classLua - 尝试创建一个好的 Vec2 类
【发布时间】:2020-07-29 16:28:11
【问题描述】:

我正在学习如何使用 Lua 和 Love2d,我想使用元方法和元表创建一个 Vec2 类。这是我目前所拥有的:

class.lua:(基类文件)

local Class = {}
Class.__index = Class

-- Constructor
function Class:new() end

-- Inherite from Class
-- type = The name of the new class
function Class:derive(type)
  print("Class:", self)
  local cls = {}
  cls["__call"] = Class.__call
  cls.type = type
  cls.__index = cls
  cls.super = self
  setmetatable(cls, self)
  return cls
end

function Class:__call(...)
  local inst = setmetatable({}, self)
  inst:new(...)
  return inst
end

function Class:getType()
  return self.type
end

return Class

vec2.lua

local class = require "class"
local Vec2 = class:derive("Vec2")

function Vec2:new(x, y)
  self.x = x or 0
  self.y = y or 0
  getmetatable(self).__add = Vec2.add
end

function Vec2.add(a, b)
  local nx, ny
  nx = a.x + b.x
  ny = a.y + b.y
  return Vec2:new(nx, ny)
end

return Vec2

在我的 main.lua 中有:

local v1 = Vec2:new(10, 10)
local v2 = Vec2:new(5, 3)
local v3 = v1 + v2
print("v3:", v3.x, v3.y)

我得到这个错误:

错误:main.lua:12:尝试在本地 'v1' 上执行算术(零 值)

【问题讨论】:

    标签: oop lua love2d metatable meta-method


    【解决方案1】:

    Vec2.new 不返回值。因此分配local v1 = Vec2:new(10,10) 导致v1nil

    改用local v1 = Vec2(10,10)Vec2.add中的同样错误

    实例是在 __call 元方法中创建的,它使用您的参数调用 new。除非您想重新初始化现有实例,否则不应直接调用 new

    function Class:__call(...)
      local inst = setmetatable({}, self)
      inst:new(...)
      return inst
    end
    

    【讨论】:

    • 现在如果我想用不同的 add 元方法添加另一个类,我该如何在不中断 Vec2.add 的情况下做到这一点?
    • @roydbt 请发布一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多