Skip to content

Commit

Permalink
refactor: improve readability and optimize toPosition function (#2928)
Browse files Browse the repository at this point in the history
Refactors the string.toPosition function to improve
readability and optimize the code. The main changes include:

• Renaming variables to more descriptive names.
• Optimized pattern matching by reusing patterns.
• Returning nil when no pattern is matched, improving error handling.

These changes make the code clearer and more efficient without altering
its functionality.
  • Loading branch information
omarcopires authored Oct 18, 2024
1 parent 665e90c commit 2735b8c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
18 changes: 0 additions & 18 deletions data-otservbr-global/lib/quests/soul_war.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1569,21 +1569,3 @@ function Creature:applyZoneEffect(var, combat, zoneName)

return true
end

function string.toPosition(str)
local patterns = {
-- table format
"{%s*x%s*=%s*(%d+)%s*,%s*y%s*=%s*(%d+)%s*,%s*z%s*=%s*(%d+)%s*}",
-- Position format
"Position%s*%((%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*%)",
-- x, y, z format
"(%d+)%s*,%s*(%d+)%s*,%s*(%d+)",
}

for _, pattern in ipairs(patterns) do
local x, y, z = string.match(str, pattern)
if x and y and z then
return Position(tonumber(x), tonumber(y), tonumber(z))
end
end
end
16 changes: 16 additions & 0 deletions data/libs/functions/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,19 @@ end
string.capitalize = function(str)
return str:gsub("%f[%a].", string.upper)
end

function string.toPosition(inputString)
local positionPatterns = {
"{%s*x%s*=%s*(%d+)%s*,%s*y%s*=%s*(%d+)%s*,%s*z%s*=%s*(%d+)%s*}",
"Position%s*%((%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*%)",
"(%d+)%s*,%s*(%d+)%s*,%s*(%d+)",
}

for _, pattern in ipairs(positionPatterns) do
local posX, posY, posZ = string.match(inputString, pattern)
if posX and posY and posZ then
return Position(tonumber(posX), tonumber(posY), tonumber(posZ))
end
end
return nil
end

0 comments on commit 2735b8c

Please sign in to comment.