Search code examples
inputluapipedefault-value

Lua script with input either piped from a command or passed as an argument with a default value


I would like to call a Lua script, say "test.lua", with an input argument through any of the following options:

  1. Piping in the output of an earlier command, say as:

    echo "value" | lua test.lua
    
  2. Appending an argument as:

    lua test.lua "value" 
    
  3. 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 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

Solution

  • 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