为什么我的lua类实现工作不正常?
问题描述:
我已经在我的lua环境中实现了OOP,但它似乎没有工作。为什么我的lua类实现工作不正常?
我认为这与我如何处理__index以及我对需求和模块的不当使用有关,但我不是100%确定的。
下面是代码:
Class = function(prototype)
local derived = {}
local derivedMT = {
--When indexing into a derived class, check the base class as well
__index = prototype,
--When invoking a class, return an instance
__call = function(proto, ...)
local instance = {}
local instanceMT = {
--When indexing into an instance, check the class hierarchy as well.
__index = derived,
--Calling instances is a no-no!
__call = function()
print("WARNING! Attempt to invoke an instance of a class!")
print(debug.traceback())
return instance
end,
}
setmetatable(instance, instanceMT)
if (instance.__constructor) then
instance:__constructor(...)
end
return instance
end,
}
setmetatable(derived, derivedMT)
return derived
end
这里是我如何使用它,在零引用的是一个基类函数的调用,即具有错误/问题IM是好像基地类没有被引用。
require "Core.Camera.FreeCamera"
local T = Core.Camera.FreeCamera.FreeCamera(0,0,-35)
c = T:getObjectType() -- nil reference
print(c .." --Type")
,这里是Camera.lua基类
local _G = _G
module(...)
local M = _G.Class()
Camera = M
function M:__constructor(x,y,z) --This never gets called.
--self.Active = false
--self.x = x
--self.y = y
--self.z = z
--self.ID = EngineManager:getCamera()
print("InCameraInstance_-_-_-_-_-__-_--_-__-_-_-_--_-_-_-_-_--_-_-_--_--__-_---_--_---__-")
end
function M:getObjectType()
return "camera"
end
终于*摄影机,它试图继承相机。
local require = require
local _G = _G
module(...)
require "Core.Camera.Camera"
local M = _G.Class(_G.Core.Camera.Camera) --Gross, lame might be the culprit
FreeCamera = M
function M:__constructor(x,y,z) ---WHOOPS, this does get called... the other one doesnt
self.Active = false
self.x = x
self.y = y
self.z = z
self.ID = _G.EngineManager:getCamera()
--_G.print("got Id of:" .. self.ID)
self:setCameraPosition(x, y, z, self.ID)
_G.print("<<<Camera in lua>>>")
end
我用尽了想法。任何帮助,将不胜感激。
答
相反的:
local M = _G.Class(_G.Core.Camera.Camera)
你需要有:
local M = _G.Class(_G.Core.Camera.Camera.Camera)
首先Camera
是目录名,第二个是模块名,第三个是类名。
编辑:你可以清理有点像这样:
local CameraModule = require "Core.Camera.Camera"
local M = _G.Class(CameraModule.Camera)
对不起,免费相机构造函数被调用......相机的犯规 – Joe 2010-02-13 00:16:47