Lua: Access the for loop variable from outside of the loop - loops

I would like to use a for-loop in Lua, but be able to identify what the last iterated value was:
local i
for i=0,10 do
if i==5 then break end
end
print(i) --always prints nil
Is there some way to prevent "i" from being re-declared in the for loop block, instead of shadowing my upvalue of the same name?
Currently, I have to use a while loop to achieve the expected results, which defeats the clarity of the for loop's syntax. Is this just another Lua caveat one has to expect as part of its language quirks?

i is local to the for-loop, meaning that you cannot access is when the loop terminates.
If you want to know what the last iterated value was, you have to save it in another variable:
local last
for i = 0, 10 do
if i == 5 then
last = i
break
end
end
print(last) --> 5

Related

Which is better between defining a variable near its context or avoid repeated allocation/initialisation?

My examples from Python, but I guess the concept applies to most languages. Suppose I have the following scenario
for element in big_list:
temp_var=something # This remains constant throughout the iterations
# Looping clause
Here, temp_var is a constant variable that is necessary within the loop. But if it remains constant, should I define it just before starting the for loop? The two conflicting principles here are
Variables should be defined with the smallest scope possible so as to not crowd the namespace. It is an argument for doing as above, which also keeps the variable closer to the context of usage.
But defining inside the loop requires repeated initialisation and allocation on each iteration. Or is it something the compiler/interpreter optimises so that I can turn a blind eye anyhow?
As the variable will not change inside the loop, I definitely choose to define it before the loop. Also, reason 1 is unuseful if variable it isn't unallocated before exiting the loop, I mean, it will remain alive after the loop. After exit the loop, you can unset the variable. So, my approach will be:
temp_var = something # This remains constant throughout the iterations
for element in big_list:
# Looping clause
# loop ended
del temp_var # If it's not needed anymore
I'm sorry I don't manage python, but I think this "code" is easily understood, and applicable to almost any language.

How can i continue the loop after getting value from function?

as i write in title, I have small question it's about loop!
i've small loop, ok?
i want pause loop in each value and call a function and wait a response from function, if function give any value i want to continue the loop!
anyone have idea or suggest to help me at this?
please don't give codes includes/or needs LUA Librares
Function calls inside loops will block by default in Lua (and any other language I can think of). So you do not have to worry about that. The loop won't continue as long the function doesn't return a value.
function is_done(x)
if x == 5 then
return true
end
return false
end
for i=1,10 do
if is_done(i) then
print('done!')
break
end
end
In the above example the loop breaks (stops) when i is equal to 5.

CS50: For Loop Design

Currently doing the CS50 lectures, and in week 2, starting at about 56:45 on this video (https://video.cs50.net/2016/fall/lectures/2?t=56m50s) he mentions that the strlen function should be moved into the initialized variable section of the for loop, rather than stay in the conditions section, because leaving it in the conditions section makes the computer run the strlen function each time the for loop increments.
Ok, I get that, but the proposed solution -- to move it into the variable declaration section, doesn't solve the problem, does it? Because it's still in the for loop, it looks like the strlen function is still being checked each time the for loop iterates.
Am I wrong?
well,strlen function will not be called every time in the for loop because we stored the value of strlen before the for loop,
it will look something like this
`int n= strlen(s);
for(int i=0;i<n;i++)
{
code
}
`
once the value of strlen is stored in n ,computer just have to access n rather than accessing strlen again and again from the string.h library
Hope this answer helps :)
the 'initialize' section of a 'for()` loop is only run once.
The 'conditional' section of a for() loop is run at the beginning of each loop iteration.
The 'step' section of a for() loop is run at the end of each loop iteration.
This is why repetitive operations, like a call to strlen() should be moved to the initialization section (where is should be setting a local variable)

Require code to perform this loop in SPSS including looping variable names

I am looking for the spss code to perform the following:
I have three variables: ResponseID and Q1 and Q2 that needs to be copied throughout my data set, I have already included variables for them - it starts with VAR00002, VAR00003 and VAR00004 several times throughout my data set. I now want to populate them, I therefore have to include the name of the variable in the loop and it needs to carry on doing this for the first set of three, the second set (VAR00005,VAR00006 and VAR00007) etc. (depending on the condition included in the Do IF). Then there is also the Else IF (and another Do If) included afterwards.
Loop # = 1 to 27
Do IF (Q[#(23)+2]=2).
COMPUTE (VAR0000(#+1))=ResponseID.
COMPUTE (VAR0000(#+2))=Q1.
COMPUTE (VAR0000(#+3))=Q2.
End if.
Else If.
Do If.
Q[(#-1)*(23)+3])=2.
DELETE VARIABLES Q[#(23)+3] TO Q623.
End If.
End Else If.
I am not sure what you need to do, but take a look at DO REPEAT, which allows you to repeat a set of transformations in a loop.
Niether I understand exactly what you are trying to do, perhaps look into LOOP / VECTOR combination

What does the variable i in for loops stand for?

Having trouble understanding what this variable is and where it gets defined:
for i in range (0, 5):
print i
Prints out number 0 - 4 like expected, but I don't understand what i means.
It's just a variable that assumes the values of the elements of an iterable object.
i is just a name chosen for the variable that holds the current array index in each loop iteration.
This is not hard coded, you can choose any name you want:
for someOtherName in range (0, 5):
print someOtherName
i is very traditional, probably comes from "index".
If you are iterating over something other than an integer index, or think your program could benefit from a more context-bearing name (such as in nested or very complex loops), you should probably give it a different name.
i is just a variable which takes values in the range. It could have been named anything within the rule defined by programming language-grammar.
This variable i is supposed to take values in the range 0 to 5 in the given code.
So, i will iterate from 0 to 4.
5 is exclusive from i as we're talking about range function which excludes the right-bound(right hand side limit).
Nothing, its just a local variable. You could call it just about anything you wanted and use that name in your loop instead.
Because when you have nested for loops the second one usually uses j as its variable and for loops, in general, can be visualized to be iterating through vectors or matrices (if nested), it could be a reference to linear algebra, where there are I and J to represent the two axes as the basis vectors.
For me, i = iteration. That's how I grab it.
From my Knowledge, It comes from FORTRAN, where variables starting with "i"
through "n" were integers.
This is how our developers started using "i" as a standard loop counter over 60 years ago

Resources