英文:
Lua script with input either piped from a command or passed as an argument with a default value
问题
我想调用一个Lua脚本,比如说"test.lua",通过以下任一方式传递输入参数:
-
通过将早期命令的输出导入,例如:
echo "value" | lua test.lua
-
作为参数附加,如下:
lua test.lua "value"
-
在脚本中设置默认参数,然后不传递任何参数,如下:
lua test.lua
为了尽可能简化,无需考虑用户混合使用上述调用方式的可能性。它们被视为互斥的,但脚本必须支持其中的任何一种情况。
我有一个包含选项2和3的最小工作示例(MWE),如下:
local params = { ... }
local val = params[1] or "default value"
至于选项1,我知道脚本可以从stdin
读取,如下:
local val = io.read("*all")
在我的实际设置中,我更愿意完整地从命令的输出中读取多行内容,而不是逐行读取,所以我使用了选项*all
。
我的问题是如何将选项1与选项2和3结合起来,因为如果我首先引入io.read()
而没有输入流,脚本会等待输入。
我考虑过测试空的stdin
,就像在https://stackoverflow.com/questions/47320496/how-to-determine-if-stdin-is-empty中提到的对C的建议一样,但我还没有找到如何在Lua中实现这一点。
将不管提供的帮助都将不胜感激。
回答后更新
根据接受的答案提出的指导原则,这是所需的功能:
local params = { ... }
local val
local pipe = io.stdin:seek('end')
if pipe then
io.stdin:seek('set')
val = io.read("*a")
else
val = params[1] or "default"
end
print(val) -- 用于测试目的
英文:
I would like to call a Lua script, say "test.lua", with an input argument through any of the following options:
-
Piping in the output of an earlier command, say as:
echo "value" | lua test.lua
-
Appending an argument as:
lua test.lua "value"
-
Setting a default argument in the script and passing no arguments at all, as:
lua test.lua
In order to make it as plain as possible, there is no need to contemplate the possibility that the user mixes any of the above callings. They are understood to be mutually incompatible, but the script must provide for any one of them to be the case.
I have an MWE encompassing options 2. and 3. as:
local params = { ... }
local val = params[1] or "default value"
As for 1., I know that the script can read from stdin
as:
local val = io.read("*all")
where I use the option *all
just because in my actual setting I'd rather read a multi-line output from the command in full rather than linewise.
My problem is how to combine option 1. with options 2. and 3, because if I introduce first io.read()
without a piped input, the script stays in the wait for an input.
I thought of testing for empty stdin
, as put forward for C
on https://stackoverflow.com/questions/47320496/how-to-determine-if-stdin-is-empty, but I haven't been able to find out how to do it in Lua.
Any help will be appreciated.
Update after answer
Following the guideline put forward on the accepted answer, this is functional as required:
local params = { ... }
local val
local pipe = io.stdin:seek('end')
if pipe then
io.stdin:seek('set')
val = io.read("*a")
else
val = params[1] or "default"
end
print(val) -- for testing purposes
答案1
得分: 2
只使用您提供的链接中的方法:
local p = io.stdin:seek('end')
if p then
io.stdin:seek('set')
local input = io.read('*a')
end
英文:
Just use the method in the link you provided
local p = io.stdin:seek('end')
if p then
io.stdin:seek('set')
local input = io.read('*a')
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论