Kosmonavt
Kosmonavt

Reputation: 191

Change step in Lua loop

I work with large amount of data using Lua. I want to move inside this circle with different steps. Very large parts of data give me losses. Small part of data gives me profit. When profit I want to move inside circle slowly with step=0.1, when losses I want to move quickly with step 1. Help me to code this.

step=1
for i=1,10000,step do
 --count profit or loss
 if PROFIT then step=0.1 
 elseif LOSS then step=1
 end
end

Upvotes: 0

Views: 1426

Answers (2)

brianolive
brianolive

Reputation: 1671

@Piglet is essentially right, but here’s another example, for clarity:

-- Create some fake data
-- 100 data points of profit and loss
local allMyData = {}
for i = 1, 100 do
    local data = math.random()
    if data < 0.5 then
        allMyData[i] = "loss!"
    else
        allMyData[i] = "profit!"
    end
end

local data = 1
local step = 1
while data < #allMyData do
    -- Adjust step
    if allMyData[data] == "profit!" then
        step = math.max(1, step - 1) -- Slow down!
    else
        step = step + 1 -- Speed up!
    end

    -- Step ahead
    data = data + step
end

Upvotes: 1

Piglet
Piglet

Reputation: 28940

From Lua Reference Manual 3.3.5 For Statement:

for v = e1, e2, e3 do block end

is equivalent to the code:

 do
   local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
   if not (var and limit and step) then error() end
   var = var - step
   while true do
     var = var + step
     if (step >= 0 and var > limit) or (step < 0 and var < limit) then
       break
     end
     local v = var
     block
   end
 end

Note the following:

All three control expressions are evaluated only once, before the loop starts. They must all result in numbers.

So changing step inside the for loops body is not going to work. If you want changing increments in your loop use a while or repeat statement with your own counter.

Upvotes: 3

Related Questions