在Lua中,我尝试使用外壳命令'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()将两个字符串都写到正确的位置呢?
发布于 2014-03-07 02:30:27
您确实需要调用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')之前,我们必须强制将缓冲的输出发送到终端。
通常,在调用任何写入同一个输出流的外部程序之前,应该刷新程序的输出缓冲区。否则,输出缓冲将使到达输出流的内容变得无序。
https://stackoverflow.com/questions/22120206
复制相似问题