【问题标题】:Is there a way to catch the output in lua?有没有办法在lua中捕获输出?
【发布时间】:2020-03-01 17:12:19
【问题描述】:

我正在尝试捕获例如 print('Hello') 的输出并将其存储在变量/表中。

如果这可能,请告诉我。如果没有,感谢您的回答。

【问题讨论】:

  • 我不知道你想做什么。您似乎在寻求一种拦截输出的方法,但 load 与输出无关。在您的示例中,print 不返回任何内容,但 load 需要字符串或函数参数。
  • 我正在尝试捕获例如 print('Hello') 的输出并将其存储在变量/表中,抱歉解释不好。

标签: lua load lua-5.2


【解决方案1】:

不能直接截取标准输出,但是可以改变全局的print函数:

local outputs = {}
local function storeOutputs(...)
  table.insert(outputs, {...})
end

local oldPrint = print
function print(...)
  storeOutputs(...)
  oldPrint(...)
end

我不确定是否有办法处理io.write 电话。

【讨论】:

  • 分配给io.stdout 不会影响io.write() 的行为。 Lua不使用io.stdout(情况和_G很相似)
  • 感谢您如此迅速地回答,而且正是我想要的!
  • @EgorSkriptunoff: 太糟糕了。我现在必须删除我答案的那一部分。可能有更复杂的方法来做到这一点,比如重写所有与输出相关的io 函数。
  • @luther - 见io.output()
猜你喜欢
  • 2012-01-12
  • 2020-02-12
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多