Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should for loop counters be local

Tags:

lua

Right now, I've been making my for loops like this

local i
for i = 1, 10 do
  --stuff
end

Since I thought you should try to keep things local for better performance and reduce risk from errors.

However, I've noticed that it is common to simply use.

for i = 1, 10 do
  --stuff
end

Is using local preferred, or is omitting it pretty harmless?

like image 917
Blubber Avatar asked Dec 25 '22 07:12

Blubber


2 Answers

(EDIT) There's no difference between the code samples you gave. However, be aware that the variable you defined with local i is not the same variable that is used within your for i = 1, 10 do loop. When the loop exits, the original value of i remains unchanged (that is, i == nil).

siffiejoe points out that loop control/counter variables are never accessible outside of the loop, even if the same variable name was defined in advance. Any references to the variable within the loop will use the loop value. Any references outside of the loop will use the original, or non-loop value.

For this reason, it's safe to reuse an existing variable name in a for statement without corrupting the original. If you want to access the counter variable after the loop, you can define an extra variable beforehand and update it at within the loop as follows (siffiejoe's example):

local j
for i = 1, 10 do
    j = i
    --[[ stuff ]]
end
print(j) -- j stores the last value of i before the loop exits

Documentation: Numeric for

like image 51
xikkub Avatar answered Jan 15 '23 22:01

xikkub


Short answer: don't add local i before the for loop, because it's useless and confusing.


The for loop starts a new block, the control variable (i here) is already local to this block. Adding the local i is similar to:

local i
do
    local i = 0
    -- do something
end

Note that the i inside the block is a totally new variable, which shadows the i outside. When the block is over, the i outside the block gets its life back, but has no knowledge of what happened inside the block because the two variables have no relationship except having the same name.

like image 30
Yu Hao Avatar answered Jan 16 '23 00:01

Yu Hao