0
votes

Recently, I have been working on a game project and decided to learn how to make a gui from scratch in love2d while I was at it. I decided to use OOP where I had menu objects and button objects within the menu objects. I had a problem where I only wanted to draw the buttons only if the menu was active. The easiest/best way to do this is probably to have a function in the menu object that checks if the menu is active and draw the buttons if it is like this...

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

This got me wondering though. Is there some way to check values in the menu's table from a function located in the button's table?

1

1 Answers

2
votes

You can use composition to access properties of Menu object from a Button. To do that you would need to pass a reference to the menu object when constructing every new Button. For instance:

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())

Would print the property name of menu from object btn.