Q:

Lua script unable to detect/catch error while executing invalid linux command

I have the following function that works fine as long as I give it a valid command to execute. As soon as I give it a non-existent command, the script is interrupted with an error message.
#!/usr/bin/lua
function exec_com(com)
    local ok,res=pcall(function() return io.popen(com) end)
    if ok then
        local tmp=res:read('*a')
        res:close()
        return ok,tmp
    else
        return ok,res
    end
end
local st,val=exec_com('uptime')
print('Executed "uptime" with status:'..tostring(st)..' and value:'..val)
st,val=exec_com('zzzz')
print('Executed "zzzz" with status:'..tostring(st)..' and value:'..val)

When I run the script above I get the following output:
Executed "uptime" with status:true and value: 18:07:38 up 1 day, 23:00,  3 users,  load average: 0.37, 0.20, 0.20

sh: zzzz: command not found
Executed "zzzz" with status:true and value:

You can clearly see above that pcall() function still reported success when executing "zzzz" which is odd. 
Can someone help me devise a way to catch an exception when executing a non-existent or ill-formed Linux command using Lua script? Thanks.
Edit: Restated my request after getting the clarification that pcall() works as expected, and the problem is due to popen() failing to throw an error.

A:

I use a method which is similar to your "temporary workaround" but which gives you more information:
local cmd = "uptime"
local f = io.popen(cmd .. " 2>&1 || echo ::ERROR::", "r")
local text = f:read "*a"

if text:find "::ERROR::" then
  -- something went wrong
  print("error: " .. text)
else
  -- all is fine!!
  print(text)
end

