Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua, what are the different forms to print?

Tags:

lua

I'm learning Lua, and I want to know the difference of print() and = or print() and io.write().

like image 232
Juan Zepeda Avatar asked Oct 19 '25 09:10

Juan Zepeda


1 Answers

This short paragraph from "Programming in Lua" explains some differences:

21.1 The Simple I/O Model

Unlike print, write adds no extra characters to the output, such as tabs or newlines. Moreover, write uses the current output file, whereas print always uses the standard output. Finally, print automatically applies tostring to its arguments, so it can also show tables, functions, and nil.

There is also following recommendation:

As a rule, you should use print for quick-and-dirty programs, or for debugging, and write when you need full control over your output

Essentially, io.write calls a write method using current output file, making io.write(x) equivalent to io.output():write(x).

And since print can only write data to the standard output, its usage is obviously limited. At the same time this guarantees that message always goes to the standard output, so you don't accidently mess up some file content, making it a better choice for debug output.

Another difference is in return value: print returns nil, while io.write returns file handle. This allows you to chain writes like that:

io.write('Hello '):write('world\n')