lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 31/12/2019 21.45, Aaron Krister Johnson wrote:
Hi all,

I am curious why 'io.write()' isn't behaving as advertised in lua5.3.*:

```
 > io.write("A nice output msg")
A nice output msgfile (0x7f8563013760)
 >
```

In particular, notice the "file (...)" bit that gets appended.

io.write works correctly, it only looks wrong in the REPL.  This is
resulting from the interplay of several features:

First, io.write always returns the file handle, so you can chain writes:

  io.write "foo" :write "bar" :write "etc.…"

Second, the REPL prints all return values.  'return 2+2' prints 4.
Saying 'return io.write "foo"' will result in exactly the behavior that
you observed. (This should also work in 5.1 IIRC?)

Third, newer versions automatically try to prepend 'return ' to anything
you type at the REPL.  (So typing '2+2' no longer throws an error but
instead says '4'.)

In combination,

  > io.write "foo"

will be read as 'return io.write "foo"', which prints "foo" and then the
return value(s) – in this case the file handle.

Try putting a semicolon in front of your statement / expression.
'return; io.write "foo"' isn't valid, which will result in it being
parsed as a statement (which doesn't return anything, and thus prints no
extra values).

-- nobody