Lua io.write() adds unwanted material to output string

Viewed 193

When I start an interactive Lua shell, io.write() adds unwanted material after the string I want it to print. print(), however does not:

[user@manjaro lua]$ lua
Lua 5.4.2  Copyright (C) 1994-2020 Lua.org, PUC-Rio
> io.write('hello world')
hello worldfile (0x7fcc979d4520)
> print('hello world')
hello world

And when I use io.write() in a program it works fine too:

--hello.lua
io.write('hello world\n')
print ('hello world')

Output:

[user@manjaro lua]$ lua hello.lua
hello world
hello world

I'm using Manjaro Linux on a Dell desktop. Can anyone tell me what's going on here? Thanks in advance.

EDIT: I should add, perhaps, that the unwanted material is always something like this:

file (0x7f346234d520)

It's always 'file' followed by what looks like a large hexadecimal number in parentheses. The exact number stays constant within one shell session but varies between different shell sessions.

1 Answers

"file (0x7fcc979d4520)" (or whatever address) is the return value of the io.write call, with an implicit tostring.

The lua(1) man page says

In interactive mode, lua prompts the user, reads lines from the standard input, and executes them as they are read. If the line contains an expression or list of expressions, then the line is evaluated and the results are printed.

The trouble here is that io.write('hello world') could be either an expression or a statement. Since it's a valid expression, the interpreter outputs that unwanted return value.

As a workaround, try adding a semicolon:

> io.write('hello world\n');
hello world    

Although Lua usually doesn't require a semicolon for each statement if it's at the end of a line, it does allow it. And important here, it means the syntax can't be an expression, only a statement which calls the function. So the interpreter won't output the returned value.

Related