Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 检查父对象中的值_Oop_User Interface_Lua - Fatal编程技术网

Oop 检查父对象中的值

Oop 检查父对象中的值,oop,user-interface,lua,Oop,User Interface,Lua,最近,我一直在做一个游戏项目,并决定学习如何在love2d中从头开始制作gui。我决定使用OOP,在菜单对象中有菜单对象和按钮对象。我遇到了一个问题,我只想在菜单处于活动状态时绘制按钮。要做到这一点,最简单/最好的方法可能是在菜单对象中有一个函数,用于检查菜单是否处于活动状态,如果是这样,则绘制按钮 menu = { -- menu stuff button = require("path") active = false, buttons = {} } function menu.newB

最近,我一直在做一个游戏项目,并决定学习如何在love2d中从头开始制作gui。我决定使用OOP,在菜单对象中有菜单对象和按钮对象。我遇到了一个问题,我只想在菜单处于活动状态时绘制按钮。要做到这一点,最简单/最好的方法可能是在菜单对象中有一个函数,用于检查菜单是否处于活动状态,如果是这样,则绘制按钮

menu = {
 -- menu stuff
button = require("path")
active = false,
buttons = {}
} 
function menu.newButton()
--create new button object from button table
end    
function menu:drawButton()

   if self.active then
       for k,v in pairs(buttons)
          menu.buttons[k]:draw() -- some draw function that sets the size, pos, and color of the button
       end
   end 
end

但这让我感到疑惑。是否有某种方法可以从按钮表中的函数检查菜单表中的值?

您可以使用composition从按钮访问菜单对象的属性。为此,在构造每个新按钮时,需要传递对
菜单
对象的引用。例如:

Button = {}

function Button.new (menu)
   return setmetatable({menu = menu}, {__index = Button})
end

function Button:getMenuName()
   return self.menu.name
end

menu = {
   name = "menu1",
   buttons = {},
}

function menu:newButton ()
   local button = Button.new(self)
   table.insert(self.buttons, button)
   return button
end

local btn = menu:newButton()
print(btn:getMenuName())

将从对象
btn

打印
menu
的属性
name
。您可以使用组合从按钮访问菜单对象的属性。为此,在构造每个新按钮时,需要传递对
菜单
对象的引用。例如:

Button = {}

function Button.new (menu)
   return setmetatable({menu = menu}, {__index = Button})
end

function Button:getMenuName()
   return self.menu.name
end

menu = {
   name = "menu1",
   buttons = {},
}

function menu:newButton ()
   local button = Button.new(self)
   table.insert(self.buttons, button)
   return button
end

local btn = menu:newButton()
print(btn:getMenuName())

将从object
btn
打印
菜单的属性
名称

很抱歉,我花了几天时间才回复。我对元表还不是很满意,但现在我已经对亚稳态做了更多的了解,这很有意义。很抱歉,我花了几天时间才回复。我对元表还不是很满意,但现在我已经对亚稳态做了更多的了解,这很有意义。