【问题标题】:Linux: tput cup with Lua acting strangeLinux: tput cup 与 Lua 行为奇怪
【发布时间】:2014-04-02 22:24:18
【问题描述】:

在 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()
  • 我试过了,所以只有第一个字符串出现('A')。

标签: linux bash terminal lua text-cursor


【解决方案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') 进行下一次调用之前,我们必须强制此缓冲输出进入终端。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多