将脚本的输出添加到Lua中的数字。

我在Linux中有一个Shell脚本,输出为10。

我想要写一个Lua脚本,将5添加到我的Shell脚本输出中。我该如何使用Shell脚本的输出?

这是我尝试的代码 -

print(5 + tonumber(os.execute('./sample')))

这是输出结果 -

10
lua: temp.lua:2: bad argument #2 to 'tonumber' (number expected, got string)
stack traceback:
    [C]: in function 'tonumber'
    temp.lua:2: in main chunk
    [C]: in ?
点赞
用户570336
用户570336

如@Etan Reisner所说,os.execute返回多个值,但是退出代码不是第一个返回值。因此,你需要将这些值存到变量中:

local ok, reason, exitcode = os.execute("./sample")
if ok and reason == "exit" then
    print(5 + exitcode)
else
    -- 进程失败或被信号终止
end

顺便说一句,如果你想将新的值作为退出代码返回,可以使用os.exit:

os.exit(5 + exitcode)

编辑:正如你在评论中澄清的那样,你想读取进程的输出(stdout),而不是它的返回值。在这种情况下,你需要使用io.popen函数:

local file = io.popen("./sample")
local value = file:read("*a")
print(5 + tonumber(value))

但请注意,io.popen在不是每个平台上都可用

2015-08-18 20:03:10