为什么我的lua类实现不起作用?

时间:2010-02-12 23:56:46

标签: lua

我已经在我的lua环境中实现了OOP,但它似乎无法正常工作。

我认为这与我如何处理__index和我对require和模块的不当使用有关,但我不是百分百肯定。

以下是代码:

    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

以下是我如何使用它,nil引用是对基类函数的调用,即错误/问题我看来基类没有被引用。

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

我的想法已经不多了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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 )