【问题标题】:Inheritance in Love2d and LuaLove2d 和 Lua 中的继承
【发布时间】:2014-06-10 02:44:04
【问题描述】:

我有一个具有这组值和函数的类:

require("class")

entity = class:new()

function entity:new()
    self.x = 100
    self.y = 100
    self.width = 32
    self.height = 32
    self.info = "entity"
    self.alive = true
    self.color = {r = 255, g = 0, b = 0}

    return self
end

function entity:load()
end

function entity:update()
    if self.alive then
    end
end

function entity:draw()
    if self.alive then
        love.graphics.setColor(self.color.r, self.color.g, self.color.b)
    end
end

function entity:destroy()
    self.alive = false
end

我希望能够将这些相同的函数和值仅用于其他类,如下所示:

require("entity")

local player = entity:new()

function player:load()
   self.color.r = 100
end

function player:update()
end
--etc etc

我来自 Flash 和 As3 背景,如果你们中的任何人知道,你可能或多或少地理解我想要做什么。 那么有人可以帮我解决这个问题吗?感谢所有帮助。

【问题讨论】:

  • 你用的是什么类库? Lua 中没有内置类。您确定entity:new() 创建的是子类而不是实体实例(如果有区别)?

标签: inheritance lua love2d


【解决方案1】:

您可以使用此class system 来获得您想要的体验。 (请务必复制完整版的代码)。

您的代码如下所示:

require("class")

entity = class()

entity.x = 100
entity.y = 100
entity.width = 32
entity.height = 32
entity.info = "entity"
entity.alive = true
entity.color = {r = 255, g = 0, b = 0}


function entity:load()
end

function entity:update()
    if self.alive then
    end
end

function entity:draw()
    if self.alive then
        love.graphics.setColor(self.color.r, self.color.g, self.color.b)
    end
end

function entity:destroy()
    self.alive = false
end

还有第二个文件:

require("entity")

local player = class()
player:addparent(entity)

function player:load()
   self.color.r = 100
end

function player:update()
end

【讨论】:

  • 谢谢。但我似乎面临的一个问题是将其应用到我的游戏中。一小部分初始化代码:-- player = player:load()enemy =enemy:load() game:add(player) game:add(enemy) (game:add() 只是将类添加到使用的表中用于渲染的 for 循环)它返回一个错误,提示“尝试索引全局 'player'(一个 nil 值)我需要该文件。
  • @user3473758 我相信您必须执行 myPlayer = player:new() myPlayer:load() 才能使您的代码正常工作。另外,如果我的回答对您有所帮助,您介意接受(按复选标记)吗?这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 2020-03-11
  • 2021-08-22
  • 2011-10-18
  • 2016-12-09
  • 1970-01-01
  • 2016-04-21
  • 2011-10-19
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多