【问题标题】:Class structure in Lua/CoronaLua/Corona 中的类结构
【发布时间】:2013-09-08 11:07:19
【问题描述】:

所以我正在使用 Lua 开发一款游戏,我正在尝试使用元表和分类,但我认为我正在导入我的 PHP 知识并稍微横向做事。

-- Basic Monster
Monster = {}

function Monster:new(newX, newY)
    local newMonster = {x = newX, y = newY}
    setmetatable(newMonster, {__index = Monster})
    return newMonster
end

function Monster:moveTo(newX, newY)
    self.x = newX
    self.y = newY
end

function Monster:takeDamage()
    self.hitPoints = self.hitPoints - playerWeapon.damage
    if self.hitPoints <= 0 then
        self.die()
    end
end

function Monster:tap()
    self.takeDamage()
end

function Monster:die()
    self.removeSelf()
end

--Groblin
Groblin = {}
setmetatable(Groblin, {__index = Monster})

function Groblin:new(newX, newY)
    local groblin = display.newImage('assets/images/goblin.png');
    groblin.hitPoints = 4
    physics.addBody(groblin, 'static')
    gameGroup.insert(groblin)
    return groblin
end

我基本上希望能够生成几种不同类型的怪物,并为它们保留一些基类功能,但我不确定在上面的示例中我如何将基类与Groblin 类联系起来我觉得我在 Groblin:new 内部所做的事情完全摧毁了那个子类。

【问题讨论】:

    标签: oop lua coronasdk metatable


    【解决方案1】:

    如果您想要可以子类化的类,请尝试使用middleclass。在标准 lua 中创建子类并不是一件容易的事,并且中间类已经处理了样板。

    另外,使用local——在任何可以使用的地方使用它。

    【讨论】:

      【解决方案2】:

      使用您的示例执行此操作的简单方法是:

      function Groblin:new(newX, newY)
        local groblin = Monster:new( newX, newY )
        setmetatable(groblin, {__index = Groblin})
        groblin.image = display.newImage('assets/images/goblin.png');
        -- ...
        return groblin
      end
      

      使用基类“:new()”方法构造对象,然后为子类添加唯一字段。这可确保正确构造基类。在子类构造函数中将元表重新设置为“Groblin”可确保调用为 Groblin 子类定义的任何方法(如果可用),并且在 Groblin 表未重新定义方法的情况下,将调用超类方法。

      使用为对象创建和子类化提供一致方法的库可能会更好,但希望这能让您更好地了解如何手动执行操作。

      【讨论】:

        【解决方案3】:

        查看http://www.lua.org/pil/16.2.html 以获得继承。 稍微注意一下关于如何在 Account:new 中使用 self 的解释,而 SpecialAccount 扩展 Account 效果最好。

        我通常采用与上述链接中提到的方法略有不同的方法。在上述方法中-

        SpecialAccount = Account:new()
        s = SpecialAccount:new{limit=1000.00}
        

        您正在调用 Account:new() 两次,当 Account:new() 对构造函数参数进行一些验证并引发异常时,会出现更多问题。例如:确保通过非零限制。

        所以我跟着这个

        SpecialAccount = setmetatable({__index = Account})
        

        是否允许在子类中使用超类构造函数。

        PS:我更喜欢将 new 函数视为构造函数。它基本上做同样的工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-04
          • 2011-09-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-28
          相关资源
          最近更新 更多