Correct way of implementing reusable button (template)?

I would probably collect the button click logic in a Lua module and only pass it the button node id and a function to call if the button was clicked. Like this:

-- button.lua

local M = {}

function M.check_click(self, node_id, action, callback)
	local node = gui.get_node(node_id)
	if gui.pick_node(node, action.x, action.y) then
		if action.released then
			gui.animate(node, gui.PROP_SCALE, 1.2, gui.EASING_INOUTQUAD, 0.3, 0, nil, gui.PLAYBACK_ONCE_PINGPONG)
			sound.play("#buttonclick")
			callback(self)
			return true
		end
	end
	return false
end

return M


-- my_ui.gui_script

local button = require("button")

function on_input(self, action_id, action)
	button.check_click(self, "button1", action, function(self) print("button1 was clicked") end)
	button.check_click(self, "button2", action, function(self) print("button2 was clicked") end)
end
2 Likes