From 8057f3e8fe016ea054fa1c878e2c90b5ae32d1b6 Mon Sep 17 00:00:00 2001 From: "Kartik K. Agaram" Date: Tue, 23 Aug 2022 10:59:58 -0700 Subject: [PATCH] stop putting button state in a global Symptom: a test (test_click_to_create_drawing) started randomly failing after I inserted a `return` 2 commits ago. Cause: my tests call edit.draw, but button handlers only get cleared in app.draw. So my tests weren't clearing button handlers, and every call to edit.draw was accumulating states. Still unclear why those were going to different state objects after the `return`, but anyway. I'm not going to understand every last thing that happens when things go wrong, just guarantee they can't go wrong. And the way to do that is to decentralize button handlers to each state that receives them. The State object in buttons.lua doesn't have to be Editor_state. It just has to be some table that provides a Schelling Point for shared state. --- button.lua | 16 ++++++++++------ edit.lua | 5 +++-- main.lua | 1 - 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/button.lua b/button.lua index 4cafc86..4c7fe0b 100644 --- a/button.lua +++ b/button.lua @@ -3,19 +3,23 @@ -- If the handler returns true, it'll prevent any further processing of the -- event. -Button_handlers = {} - -- draw button and queue up event handlers -function button(name, params) +function button(State, name, params) + if State.button_handlers == nil then + State.button_handlers = {} + end love.graphics.setColor(params.color[1], params.color[2], params.color[3]) love.graphics.rectangle('fill', params.x,params.y, params.w,params.h, 5,5) if params.icon then params.icon(params.x, params.y) end - table.insert(Button_handlers, params) + table.insert(State.button_handlers, params) end -- process button event handlers -function propagate_to_button_handlers(x, y, mouse_button) - for _,ev in ipairs(Button_handlers) do +function propagate_to_button_handlers(State, x, y, mouse_button) + if State.button_handlers == nil then + return + end + for _,ev in ipairs(State.button_handlers) do if x>ev.x and xev.y and y