Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - why for loop limit is not calculated dynamically?

Ok here's a basic for loop

local a = {"first","second","third","fourth"}
for i=1,#a do 
    print(i.."th iteration")
    a = {"first"}
end 

As it is now, the loop executes all 4 iterations.

Shouldn't the for-loop-limit be calculated on the go? If it is calculated dynamically, #a would be 1 at the end of the first iteration and the for loop would break....

Surely that would make more sense? Or is there any particular reason as to why that is not the case?

like image 957
SatheeshJM Avatar asked Jul 29 '26 02:07

SatheeshJM


1 Answers

The main reason why numerical for loops limits are computed only once is most certainly for performance.

With the current behavior, you can place arbitrary complex expressions in for loops limits without a performance penalty, including function calls. For example:

local prod = 1
for i = computeStartLoop(), computeEndLoop(), computeStep() do
  prod = prod * i
end

The above code would be really slow if computeEndLoop and computeStep required to be called at each iteration.

If the standard Lua interpreter and most notably LuaJIT are so fast compared to other scripting languages, it is because a number of Lua features have been designed with performance in mind.


In the rare cases where the single evaluation behavior is undesirable, it is easy to replace the for loop with a generic loop using while end or repeat until.

local prod = 1
local i = computeStartLoop()
while i <= computeEndLoop() do
  prod = prod * i
  i = i + computeStep()
end
like image 69
prapin Avatar answered Jul 30 '26 20:07

prapin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!