[英]Lua OOP multiple instances of class are being ignored, why?
I have a class called "Edit"我有一个名为“编辑”的 class
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
and that class has a function called draw(made with Löve2d)并且 class 有一个名为 draw 的 function(用 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
and in my main i create 2 of them我主要创建了其中的 2 个
edit1 = Edit:new(10,10,60,50,"1")
edit2 = Edit:new(80,10,60,50,"2")
and draw them in the callback并在回调中绘制它们
function love.draw( )
edit1:draw()
edit2:draw()
end
but it only draws edit2?但它只绘制edit2? if i switch the places in draw it still only draws edit2 but if i switch their places while creating them in the main it now only draws edit1?
如果我在draw中切换位置,它仍然只绘制edit2,但如果我在主创建它们时切换它们的位置,它现在只绘制edit1?
This is the most common beginners mistake when they get into OOP in Lua.这是初学者在 Lua 中进入 OOP 时最常见的错误。
You're assigning all those values to self
which is Edit
.您将所有这些值分配给
self
,即Edit
。 But if you want to change your instance you need to assign them to o
.但是如果你想改变你的实例,你需要将它们分配给
o
。
Otherwise each call to Edit.new
will overwrite the values.否则每次调用
Edit.new
都会覆盖这些值。
The second problem is that your instance o
is a global.第二个问题是您的实例
o
是全局的。 You need it to be local.你需要它是本地的。 Or you will overwrite your instances each time.
或者您每次都会覆盖您的实例。
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
Read this:读这个:
https://www.lua.org/pil/16.html https://www.lua.org/pil/16.html
http://lua-users.org/wiki/ObjectOrientedProgramming http://lua-users.org/wiki/ObjectOrientedProgramming
You initiates your object not quite correct.您启动 object 不太正确。
In new
function you initiates your object and self
in this function is your metatatable.在
new
的 function 中,您启动 object 和self
在此 function 是您的元表。
The other problem that you creates global object o
.您创建全局 object
o
的另一个问题。
So your new function must be:所以你的新 function 必须是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.