Lua - 尝试创建一个好的Vec2类

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

class.lua:(基类文件)

local Class = {}
Class.__index = Class

-- 构造函数
function Class:new() end

-- 从Class继承
-- type = 新类的名称
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)

我得到了这个错误:

Error: main.lua:12: 指定的变量v1为 nil

点赞
用户2858170
用户2858170

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

尝试使用 local v1 = Vec2(10,10)。在 Vec2.add 中同样的错误。

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

function Class:__call(...)
  local inst = setmetatable({}, self)
  inst:new(...)
  return inst
end
2020-04-16 13:19:14