For i in print?

Recently I stumbled across this code block, it’s a for loop, but in print. I was just curious into how this works, and when I could potentially use it. What I know so far is that the first argument is a string, and the second argument is a string.

Code:

for i in print, "Hello world", "" do break end

Output:

Hello world

Code:

for i in print, "Hello world", " Hello World" do break end

Output:

Hello world Hello World
1 Like

This just looks like a mis-use of iterators. It works with any function because iterators are passed as iterator, state, index.

Every loop, iterator(state, index) is called, and the result uses for the loop variables if not nil, while index gets updated accordingly.

What you are seeing is just an obfuscated way of calling print and then breaking out of the loop right away.

4 Likes

I have an article that covers what Autterfly is talking about if it interests you

4 Likes

Thanks, really widens my understanding of loops.

1 Like

I assume in the case I provided “print” would be the “function” and “i” is the index. What I don’t really understand is that normally in the loops you provided, the table is the argument inside of the function, in this case however “Hello world” is not a table, and is not inside of the print(). Is “Hello world” in a table on its own and i is 1?

Iterators don’t actually have any requirements in what each type is.

for _ in a, b, c

will simply be called as

a(b, c)

So as long as a is callable, it will be called with b and c until it returns nil.

3 Likes

Just like Autter said lua doesn’t seem to care what you give it so it doesn’t error if you give it. What happens is it just calls print, which is supposedly the iterator, until it returns nil (this is how iterators work, keep on incrementing an internal state, and returning something each time until they return nil and the loop stops). Now print doesn’t return anything in the first place, meaning it will just be called once, does the printing side effect, and the loop actually doesn’t loop because a nil was returned since the first iteration!. You can even try printing the i or do anything else, and nothing happens.

for i in print, "Hello world", " Hello World" do
   print("hi") --doesn't print hi not even once, the loop didn't even loop because the iterator we passed, which is print, returned nil at the first iteration
end
1 Like