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
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?
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