我正在学习如何使用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'执行算术运算(nil值)
Vec2.new
不返回值。因此,分配local v1 = Vec2:new(10,10)
导致v1
为nil
改为尝试local v1 = Vec2(10,10)
。 Vec2.add中的相同错误