OpenNefia icon indicating copy to clipboard operation
OpenNefia copied to clipboard

Don't mutate state of things like UiLIst when wanting to pass a result to the parent element

Open Ruin0x11 opened this issue 4 years ago • 1 comments
trafficstars

Instead of:

function MyList:choose()
   self.chosen = true
end

function MyList:update(dt)
   self.chosen = false
end
function MyLayer:init()
   self.list = MyList:new()
   self.win = UiWindow:new()
end

function MyLayer:update(dt)
   if self.list.chosen then
      return self.list.chosen, nil
   end

   self.list:update(dt)
   self.win:update(dt)

   if self.canceled then
      return nil, "canceled"
   end
end

Do this:

function MyList:choose()
   self.chosen = true
end

function MyList:update(dt)
   local chosen = self.chosen
   self.chosen = false

   if chosen then
      return self.list:selected_index(), nil
   end
end
function MyLayer:init()
   self.list = MyList:new()
   self.win = UiWindow:new()
end

function MyLayer:update(dt)
   local state = self.list:update(dt)
   local canceled = self.canceled

   self.win:update(dt)
   self.canceled = false

   if chosen then
      return chosen, nil
   end
   if canceled then
      return nil, "canceled"
   end
end

Ruin0x11 avatar Feb 21 '21 19:02 Ruin0x11

Maybe the update and the return should be two separate functions instead, so you can call only one if you want. It would make refactoring the layers to be "reentrant" easier.

Ruin0x11 avatar Mar 15 '21 06:03 Ruin0x11