How do you construct a read-write pipe with lua?

后端 未结 7 1136
甜味超标
甜味超标 2020-12-09 04:26

I\'d like to do the equivalent of:

foo=$(echo \"$foo\"|someprogram)

within lua -- ie, I\'ve got a variable containing a bunch of text, and

7条回答
  •  感动是毒
    2020-12-09 05:07

    As long as your Lua supports io.popen, this problem is easy. The solution is exactly as you have outlined, except instead of $(...) you need a function like this one:

    function os.capture(cmd, raw)
      local f = assert(io.popen(cmd, 'r'))
      local s = assert(f:read('*a'))
      f:close()
      if raw then return s end
      s = string.gsub(s, '^%s+', '')
      s = string.gsub(s, '%s+$', '')
      s = string.gsub(s, '[\n\r]+', ' ')
      return s
    end
    

    You can then call

    local foo = ...
    local cmd = ("echo $foo | someprogram"):gsub('$foo', foo)
    foo = os.capture(cmd)
    

    I do stuff like this all the time. Here's a related useful function for forming commands:

    local quote_me = '[^%w%+%-%=%@%_%/]' -- complement (needn't quote)
    local strfind = string.find
    
    function os.quote(s)
      if strfind(s, quote_me) or s == '' then
        return "'" .. string.gsub(s, "'", [['"'"']]) .. "'"
      else
        return s
      end
    end
    

提交回复
热议问题