xrotors
xrotors

Reputation: 7

How to iterate multiple ranges together in LUA

I have this situation:

n1 = variable_1 -- 0,154
n2 = variable_2 -- 335565,418338
n3 = variable_3 -- -0.2,-3.2

for n1 = 0,154 do -- range of n1
    -- proportionally increase/decrease n2
    -- proportionally increase/decrease n3
end

I want to increase/decrease n2 and n3 along with n1 within their own ranges. Is a for loop the best solution?

Upvotes: 0

Views: 254

Answers (1)

Piglet
Piglet

Reputation: 28950

https://en.wikipedia.org/wiki/Linear_interpolation

function lerp(v0, v1, t)
  return (1 - t) * v0 + t * v1;
end

local n1 = {0, 154}
local n2 = {335565, 418338}
local n3 = {-0.2, -3.2}

for i = n1[1], n1[2] do
  local t = i / n1[2]
  print(i, lerp(n2[1], n2[2], t), lerp(n3[1], n3[2], t))
end

Edit:

In my actual script n1 is a range of an already declared variable named as the_speed as well as n2 which is named eng_pow_max and n3 which name is sidecant. How can I read the_speed value and write it into i?

The for loop is just to print values across the entire interval.

You need to know a few things.

  1. the maximum speed, assuming speed starts at 0
  2. the range of eng_pow_max
  3. the range of sidecant
  4. the acutal speed you want to calculate the other values for

First we calculate the speed ratio. the_speed / max_speed gives you a value between 0 and 1.

0 / 154 is 0 (0% speed) 77/154 is 0.5 (50% speed)

I hope you get the point.

Now we can use the lerp function to calculate the other 2 values

local eng_pow = lerp(eng_pow_min, eng_pow_max, the_speed / max_speed)

local sidecant = lerp(side_cant_min, sidecant_max, the_speed / max_speed)

Upvotes: 2

Related Questions