There's 1 real optimization & 3 micro-optimizations I can spot.
Real optimization:
- Dynamically store the results of each unique radius, this should be feasible considering they'll always run the loop on integers.
Micro-optimizations:
- Create a variable for radius^2 so it's only calculated once instead of twice.
- Use table.insert for arrays instead of manually setting the index-value.
- Have dx & dy set at the same time so there isn't a need for the variable
temp.
local CachedResults = {}
function spiral(radius)
local resoult = CachedResults[radius]
if resoult ~= nil then
return resoult
end
local radius2 = radius ^ 2
resoult = table.create(radius2)
local dx, dy = 1,0
local x, y = 0, 0
local segmentLength = 1
local segmentPassed = 0
for i = 1, radius2 do
table.insert(resoult, Vector2.new(x, y))
x += dx
y += dy
segmentPassed += 1
if segmentPassed == segmentLength then
segmentPassed = 0
dx, dy = -dy, dx
if dy == 0 then
segmentLength += 1
end
end
end
CachedResults[radius] = resoult
return resoult
end