Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua io.write()将不需要的内容添加到输出字符串中_Lua - Fatal编程技术网

Lua io.write()将不需要的内容添加到输出字符串中

Lua io.write()将不需要的内容添加到输出字符串中,lua,Lua,启动交互式LuaShell时,io.write()会在希望打印的字符串后添加不需要的内容打印(),但不: [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 当我在程序中使用io.write()时,

启动交互式LuaShell时,
io.write()
会在希望打印的字符串后添加不需要的内容<代码>打印(),但不:

[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
当我在程序中使用
io.write()
时,它也可以正常工作:

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

[user@manjaro lua]$ lua hello.lua
hello world
hello world
我正在戴尔桌面上使用Manjaro Linux。谁能告诉我这里发生了什么事?提前谢谢

编辑:我应该补充一点,也许不需要的材料总是这样的:

file (0x7f346234d520)
它总是在“file”后面加上一个大的十六进制数。在一个shell会话中,确切的数字保持不变,但在不同的shell会话中会有所不同。

文件(0x7fcc979d4520)
”(或任何地址)是
io.write
调用的返回值,带有隐式
tostring

lua(1)手册页上说

在交互模式下,
lua
提示用户,从标准输入中读取行,并在读取时执行。如果该行包含表达式或表达式列表,则对该行求值并打印结果

这里的问题是,
io.write('hello world')
可以是表达式或语句。因为它是一个有效的表达式,所以解释器输出不需要的返回值

作为解决方法,请尝试添加分号:

> io.write('hello world\n');
hello world    
虽然Lua通常不要求在每一行末尾的语句都使用分号,但它确实允许使用分号。重要的是,这里的语法不能是表达式,只能是调用函数的语句。因此解释器不会输出返回的值。

您可以执行
io.flush()
使其行为类似于
print()

…作为一种副作用,它还具有等待或睡眠功能。
阅读答案:
(讨论中的评论也很有趣;-)

要糖吗

do io.write('hello world\n'):flush() end
…如果你有一个等待函数,其中一百万是一秒,那么你可以

io.stdout:setvbuf('no')
local _,str=pcall(assert,io.write)
str('hello')
wait(1000000)
str(' world\n')
wait(1000000)
str('...with ')
wait(1000000)
str(_VERSION..'\n')

io.write
相当于
io.open():write()
io.open()
返回文件句柄(默认输出文件)
file:write()
成功返回
file
,因此您最终可以在
hello world
之后看到该文件句柄的字符串表示形式<代码>打印不会返回值,因此您不会看到任何额外的文本。谢谢。这是正常的行为吗?我只是Lua的初学者,但我可以发誓,上一次使用Lua交互模式时,几天前没有发生这种情况。官方在线手册中包含了不带分号的
io.write()
语句,这些语句不会表现出这种行为:。我真的不知道。可能是Lua版本的不同。这可能取决于操作系统或使用的二进制文件。例如,我在使用LuaDist的Windows下没有观察到这种情况。这种行为是在Lua5.3中引入的。这是对原始问题的错误回答,即使其中的一些想法可能有用。消息由交互式shell打印,添加
io.flush()
正好可以解决这个问题。此外,删除
do。。。从第二个示例结束
,完全相同的问题又出现了,证明它确实是由语法引起的副作用,而不是完全相同的问题;-)-第二个示例从
flush()
返回true,可通过以下方式处理:
do local rc=io.write('hello world\n'):flush()如果rc,那么io.write('success\n')end
,事实上,没有理由不使用do。。。无论你/我们/我想在哪里结束。特别是使用局部变量:descibes这确实是真的。正如我所说的,这个答案有一些有用的想法,但并不能正确回答所提出的问题。
io.stdout:setvbuf('no')
local _,str=pcall(assert,io.write)
str('hello')
wait(1000000)
str(' world\n')
wait(1000000)
str('...with ')
wait(1000000)
str(_VERSION..'\n')