OpenNefia
OpenNefia copied to clipboard
Don't mutate state of things like UiLIst when wanting to pass a result to the parent element
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
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.