I'm learning Lua, and I want to know the difference of print() and = or print() and io.write().
This short paragraph from "Programming in Lua" explains some differences:
21.1 The Simple I/O Model
Unlike
writeadds no extra characters to the output, such as tabs or newlines. Moreover,writeuses the current output file, whereastostringto its arguments, so it can also show tables, functions, andnil.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With