2010-02-12 57 views
2

我已经在我的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 

我用尽了想法。任何帮助,将不胜感激。

+0

对不起,免费相机构造函数被调用......相机的犯规 – Joe 2010-02-13 00:16:47

回答

5

相反的:

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) 
+0

哇...这是讨厌...感谢这么很多的帮助...我希望有一种方法来清理它。 – Joe 2010-02-13 00:46:34

+0

@Joe,有一种方法 - 请参阅编辑。 – interjay 2010-02-13 00:58:28

+0

甜,谢谢一堆。 – Joe 2010-02-13 01:16:00