Skip to content

Commit

Permalink
fix: infinite loop in Zone:randomPosition when no valid tile exist (#…
Browse files Browse the repository at this point in the history
…3178)


This commit fixes an infinite loop issue in the `Zone:randomPosition`
function. When no valid positions (walkable tiles) exist in the zone,
the function would previously enter an infinite loop. The updated logic
now filters all positions upfront to identify walkable tiles, and if
none are found, the function returns `nil` with appropriate logging.
This change ensures better error handling and prevents server freezes
due to infinite loops.
  • Loading branch information
dudantas authored Dec 14, 2024
1 parent 60dd514 commit 61c1fc0
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions data/libs/systems/zones.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,24 @@ function Zone:randomPosition()
logger.error("Zone:randomPosition() - Zone {} has no positions", self:getName())
return nil
end
local destination = positions[math.random(1, #positions)]
local tile = destination:getTile()
while not tile or not tile:isWalkable(false, false, false, false, true) do
destination = positions[math.random(1, #positions)]
tile = destination:getTile()

local validPositions = {}
for _, position in ipairs(positions) do
local tile = position:getTile()
if tile and tile:isWalkable(false, false, false, false, true) then
table.insert(validPositions, position)
else
logger.debug("Zone:randomPosition() - Position {} is invalid (Tile: {}, Walkable: {})", position, tile or "nil", tile and tile:isWalkable(false, false, false, false, true) or "false")
end
end

if #validPositions == 0 then
logger.error("Zone:randomPosition() - No valid positions in Zone {}", self:getName())
return nil
end

local destination = validPositions[math.random(1, #validPositions)]
logger.debug("Zone:randomPosition() - Selected valid position: {}", destination)
return destination
end

Expand Down

0 comments on commit 61c1fc0

Please sign in to comment.