如何在 Lua 中清除标准输出行?

你有一个 Lua 函数来模拟进度完成并输出到 stdout

function progress(completed)
  io.write(completed.."\r")
  io.flush()
end

progress("1% completed"); progress("50% completed")

输出结果为

% completed

部分文本消失了。在 python 的类似情况中,我可能会在向 stdout 写入以下文本之前清除行:

sys.stdout.write(' ' * 50 + '\r')
sys.stdout.write(text + '\r')
sys.stdout.flush()

如何在 Lua 中清除 stdout 行?

我会这样做,但是有更好或更标准的方法吗?

function iop(str)
  io.write(string.format("%050s\r", ' '))
  io.write(str)
  io.flush()
end
点赞
用户1847592
用户1847592
local last_str = ''

function iop(str)
   io.write(('\b \b'):rep(#last_str))  -- 擦除旧字符
   io.write(str)                       -- 输出新字符
   io.flush()
   last_str = str
end

现在让我们来测试一下:

function wait(msec)
   local t = os.clock()
   repeat
   until os.clock() > t + msec * 1e-3
end

iop('非常非常非常长的字符串')
wait(500)
for i = 0, 100 do
   iop(i..'% 完成')
   wait(20)  -- 等待 20 毫秒
end
print'\n完成了'
2017-01-21 21:56:22