Murga-Projects Forums

Full Version: io.write() vs. my_output:write()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wonder if someone could help me understand when to choose one over the other.
Consider the following:

if my_output then my_output:write("some stuff")

io.write("some stuff")

Both apparently have a similar result, although with io.write() there doesn't seem to be a way to prevent a fatal error when the file can't be written.

io.write is really io.stdout:write

Using io.output you are really redirecting stdout.

When used with an argument it becomes the new default output and as such is opened in the "w" mode, i.e, to overwrite if it exists, or to create if it does not exist..

Changing the default output can be risky when you don't have permission, as you have noted. But can be useful in a quick and dirty sort of way.

Usually, I use the full file handle method as in your first example. This provides better control over error conditions.
Thanks for the explanation. I had a feeling that it was opening a standard output, but some tests made me wonder. For example, if you do this:

print("some text")

the file is still created, but "some text" is printed to terminal as usual instead of to the file (i'm not sure what would happen in Windows). Maybe print() doesn't go to stdout?

In any case, I prefer the file:write() method. It seems more logical to me that if you want to write to a specific file you'd set up a specific output just for the data you want to write to that file.

I guess it's yet another case of having options, whether you want to use them or not.

I belive print is a special case as the print function is not really suitable for general file writing.

The print function does things to the data that io.write does not.
1. Converts everything to a string
2. Separates multiple arguments with tabs
3. Always appends a newline

This is great when used as a debugging tool using the old method of peppering your script with print statements. It is also useful to inspecting properties of variables, tables, etc.

But it would really mess up when trying to write to a real file.

I suppose you could define a new print function in your script that would you could use instead of io.write.

I am guessing that the system's print function saves the current stdout assignment, then sets to a normal stdout, the screen, and afterwards reassigns the saved stdout.
I see. I tried redirecting stderr to stdout thinking that maybe print() was being sent to stderr instead.
It makes sense that print() would be a special case.

This is great when used as a debugging tool using the old method of peppering your script with print statements.

I do this for nearly every script I make. It's extremely handy =o)

Reference URL's