是否可以从Lua中的局部变量中读取以下内容?
local t = os.execute("echo 'test'")
print(t)
我只是想实现这个:每当
os.execute
返回任何值时,我想在Lua中使用它 - 例如echo 'test'
将在bash命令行中输出test
- 是否有可能获得返回值( test
在这种情况下)到 Lua 局部变量?
io.popen()
。这将返回一个文件句柄,您可以使用它来读取命令的输出。像下面这样的东西可能会起作用:
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
请注意,这将包括命令发出的尾随换行符(如果有)。
function GetFiles(mask)
local files = {}
local tmpfile = '/tmp/stmp.txt'
os.execute('ls -1 '..mask..' > '..tmpfile)
local f = io.open(tmpfile)
if not f then return files end
local k = 1
for line in f:lines() do
files[k] = line
k = k + 1
end
f:close()
return files
end
io.popen
比 os.execute
更适合此用例。后者只返回退出状态而不是输出。
-- runs command on a sub-process.
local handle = io.popen('cmd')
-- reads command output.
local output = handle:read('*a')
-- replaces any newline with a space
local format = output:gsub('[\n\r]', ' ')
工作示例:
local handle = io.popen('date +"%T.%6N"')
local output = handle:read('*a')
local time = output:gsub('[\n\r]', ' ')
handle:close()
print(time .. 'DEBUG: Time recorded when this event happened.')
Lua 的
os.capture
返回所有标准输出,因此它将返回到该变量中。
例子:
local result = os.capture("echo hallo")
print(result)
印刷:
hallo
对不起, 但这是不可能的。 如果 echo 程序成功退出,它将返回 0。这个返回码是 os.execute() 函数得到并返回的。
if 0 == os.execute("echo 'test'") then
local t = "test"
end
这是一个得到你想要的东西的方法,我希望它能帮助到你。
获取函数返回码的另一个技巧是 Lua 引用。 Lua-参考/教程