Juan Zepeda
Juan Zepeda

Reputation: 53

In Lua, what are the different forms to print?

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

Upvotes: 4

Views: 2015

Answers (2)

IS4
IS4

Reputation: 13207

print is used for outputting text messages. It joins its arguments with a tab character, and automatically inserts a newline.

io.write is more simple. While it also accepts any number of arguments, it simply concatenates them (without inserting any characters) and doesn't add any newline. Think of it as file:write applied to the standard output.

These lines are equivalent:

io.write("abc")
io.write("a", "b", "c")
io.write("a") io.write("b") io.write("c")

I'd recommend using print for outputting normal text messages, or for debug, and io.write when you either want to print a number of strings without concatenating them explicitly (using io.write saves more memory), be able to write parts of a text separately, or outputting binary data via strings.

Upvotes: 4

user1143634
user1143634

Reputation:

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')

Upvotes: 7

Related Questions