Linux:TPUTCup和Lua的行为很奇怪

Linux:TPUTCup和Lua的行为很奇怪,linux,bash,lua,terminal,cursor,Linux,Bash,Lua,Terminal,Cursor,在Lua中,我尝试使用shell命令“tput cup foo bar”移动光标,并使用“io.write('foo')”在该位置写入字符串 os.execute('tput clear') --clear terminal os.execute('tput cup 2 9') --move cursor to line 2, col 9 io.write('A') --write 'A' at the cursor position os.execute('

在Lua中,我尝试使用shell命令“tput cup foo bar”移动光标,并使用“io.write('foo')”在该位置写入字符串

os.execute('tput clear')    --clear terminal
os.execute('tput cup 2 9')  --move cursor to line 2, col 9
io.write('A')               --write 'A' at the cursor position
os.execute('tput cup 8 2')  --move cursor to line 8, col 2
io.write('B')               --write 'B' at the cursor position
但是,由于某些原因,它会在第二个光标位置(第2列第8行)打印两个字符


但是,当我使用print()而不是io.write()时,它会在两个字符的正确位置打印这两个字符。出于明显的原因,我不想使用print(),因此如何使用io.write()将两个字符串写入正确的位置?

您确实需要调用
io.flush()
@lhf提出了正确的建议。但诀窍在于,您需要在代码中的正确位置使用它

os.execute('tput clear')    --clear terminal
os.execute('tput cup 2 9')  --move cursor to line 2, col 9
io.write('A')               --write 'A' at the cursor position
io.flush()                  --*** this is what was missing
os.execute('tput cup 8 2')  --move cursor to line 8, col 2
io.write('B')               --write 'B' at the cursor position
输出将发送到终端,有两个程序竞争写入终端:Lua和tput。对
io.execute('tput')
的前两个调用立即写入终端。调用
io.write()
将字母“A”放入Lua的内部输出缓冲区。在下一次调用
io.execute('tput')
之前,我们必须强制这个缓冲输出进入终端


通常,在调用任何写入同一输出流的外部程序之前,应该刷新程序的输出缓冲区。否则,输出缓冲将使输出流中的内容无序到达。

您可能需要在写入后调用
io.flush()
。我尝试了这个方法,使它只出现第一个字符串('A')。