在Lua

2015-08-18 32 views
0

添加腳本輸出了一些我在Linux的一個shell腳本輸出10在Lua

我想寫在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 ? 
+1

你需要io.popen。 – lhf

回答

4

正如@Etan賴斯納表示,os.execute是返回多個值,但是,退出代碼不是第一個返回值。因此,你必須將這些值塞進變量:

local ok, reason, exitcode = os.execute("./sample") 
if ok and reason == "exit" then 
    print(5 + exitcode) 
else 
    -- The process failed or was terminated by a signal 
end 

順便說一句,如果你想返回新值作爲退出代碼,你可以這樣做使用os.exit:

os.exit(5 + exitcode) 

編輯:正如您已通過評論澄清,您正在閱讀輸出(標準輸出)的過程,而不是它的返回值。在這種情況下,io.popen是你需要的功能:

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

但是請注意,這是io.popen not available on every plattform

+0

我得到0作爲退出代碼,一件事,爲什麼我需要從我的shell腳本退出代碼? shell腳本只包含'echo 10' – Yashar

+1

請參閱我的編輯;您需要io.popen才能啓動該進程並獲取其stdout的句柄 –