Linux:用Lua表演奇怪的tput杯

时间:2014-03-01 20:52:03

标签: 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('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()将两个字符串写入正确的位置?

1 个答案:

答案 0 :(得分:1)

您需要致电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')之前,我们必须强制这个缓冲输出到终端。

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

相关问题