【问题标题】:Lua OOP multiple instances of class are being ignored, why?Lua OOP 类的多个实例被忽略,为什么?
【发布时间】:2021-03-26 17:37:11
【问题描述】:

我有一个名为“编辑”的课程

function Edit:new(x,y,w,h,text,fnt)
    o = {}
    setmetatable(o,EditMt)
    self.__index = self
    self.x = x or 0
    self.y = y or 0
    self.width = w or 10
    self.height = h or 10
    self.text = text or ""
    self.active = false
    self.font = fnt or font
    self.yo = -(self.height - self.font:getHeight()) / 2
    return o
end

并且该类有一个名为 draw(使用 Löve2d 制作)的函数

function Edit:draw(  )
    if self.active then
        love.graphics.setColor(255,255,255,255)
     love.graphics.rectangle("fill",self.x,self.y,self.width,self.height)
        love.graphics.setColor(0,0,0,255)
        love.graphics.printf(self.text,self.font,self.x,self.y,self.width, "center",0,1,1,0,self.yo)
    else 
        love.graphics.setColor(255,255,255,255)
        love.graphics.rectangle("line",self.x,self.y,self.width,self.height)
        love.graphics.printf(self.text,self.font,self.x,self.y,self.width, "center",0,1,1,0,self.yo)
    end
end

我主要创建了 2 个

edit1 = Edit:new(10,10,60,50,"1")
edit2 = Edit:new(80,10,60,50,"2")

并在回调中绘制它们

function love.draw( )
    edit1:draw()
    edit2:draw()
end

但它只绘制edit2?如果我在draw中切换位置,它仍然只绘制edit2,但如果我在主创建它们时切换它们的位置,它现在只绘制edit1?

【问题讨论】:

    标签: oop lua


    【解决方案1】:

    这是初学者在 Lua 中接触 OOP 时最常见的错误。

    您将所有这些值分配给self,即Edit。但是如果你想改变你的实例,你需要将它们分配给o

    否则每次调用Edit.new 都会覆盖这些值。

    第二个问题是您的实例o 是一个全局的。你需要它是本地的!否则您将每次都覆盖您的实例。

     function Edit:new (x,y,w,h,text,fnt)
          local o = {}   
          setmetatable(o, self)
          self.__index = self
          o.x = x or 0
          o.y = y or 0 
          -- and so forth
          return o
        end
    

    阅读:

    https://www.lua.org/pil/16.html

    http://lua-users.org/wiki/ObjectOrientedProgramming

    【讨论】:

      【解决方案2】:

      您启动的对象不太正确。

      new 函数中你启动你的对象,self 在这个函数中是你的元表。

      你创建全局对象o的另一个问题。

      所以你的新函数必须是:

      function Edit:new(x,y,w,h,text,fnt)
          local o = {}
          setmetatable(o, self)
          self.__index = self
          o.x = x or 0
          o.y = y or 0
          o.width = w or 10
          o.height = h or 10
          o.text = text or ""
          o.active = false
          o.font = fnt or font
          o.yo = -(o.height - o.font:getHeight()) / 2
          return o
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-09
        • 2021-11-06
        • 2019-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多