Reputation: 2161
I was doing some calculations to use as the testcases for a question I'm going to post on PCCG Stack Exchange, and I noticed that in a piece of code like this:
for i = 0, 20 do
io.write(i..": ")
diff(i)
end
(where diff
is a function which does some pretty heavy calculation and prints the result), the result of diff
is first calculated and, only then, i:
and the result of diff
are printed.
But why is this happening? Shouldn't I see i:
before and during the calculation, and the result of the calculation only after? Why is it waiting for diff
to execute before?
I first noticed this using Luajit, but it also happens on vanilla Lua and even outside of a for
loop.
Upvotes: 2
Views: 54
Reputation: 22421
Just as with many other output functions in many other languages, io.write
output is buffered. It is evaluated, it is just your output is now in intermediate buffer pending flushing or filling of this buffer. Add an io.flush()
call if you need your data to go through right now.
Upvotes: 5