简体   繁体   English

Love2d和Lua中的继承

[英]Inheritance in Love2d and Lua

I have a class with this set of values and functions: 我有一个带有这组值和函数的类:

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

And I want to be able to use those same functions and values simply for other classes, like so: 我希望能够仅将这些相同的函数和值用于其他类,例如:

require("entity")

local player = entity:new()

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

function player:update()
end
--etc etc

I come from a flash and As3 background, which if any of you know you may understand more or less what I'm trying to do. 我来自Flash和As3背景,如果您知道的话,您可能或多或少地了解我正在尝试做的事情。 So could anyone help me with this? 那么有人可以帮我吗? All help is appreciated. 感谢所有帮助。

You can use this class system to get the experience you are desiring to have. 您可以使用此类系统来获取您想要的体验。 (Make sure to copy the code of the full version). (确保复制完整版本的代码)。

Your code would look like this: 您的代码如下所示:

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

And the second file: 第二个文件:

require("entity")

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

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

function player:update()
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM