Search code examples
lua

Lua - Using string.find to find a sentence?


Following a previous Stack Overflow response, (here) I am trying to check if a particular sentence/string is returned in the response of a io.popen command I’m running..

local function DevicePing(ip)
    local handler = io.popen("ping -c 3 " ..ip.. " 2>&1")
    local response = handler:read("*a")
    print(response)
    if string.find(response, "0% packet loss") then
        print ("Pings were all successfull.")
    else
        print ("Pings were all unsuccessfull.")
    end
end

DevicePing("192.168.1.180")

But every time I run it, it doesn’t find the requested string/sentence; see the print output below..

PING 192.168.1.180 (192.168.1.180): 56 data bytes
64 bytes from 192.168.1.180: seq=0 ttl=64 time=2.983 ms
64 bytes from 192.168.1.180: seq=1 ttl=64 time=1.620 ms
64 bytes from 192.168.1.180: seq=2 ttl=64 time=2.465 ms

--- 192.168.1.180 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 1.620/2.356/2.983 ms
     
Pings were all unsuccessfull.     

What am I doing wrong for it not to see ‘0% packet loss‘ is present and say it was successfull?


Solution

  • % is the escape character in Lua patterns. Use "0%% packet loss" to mean a literal %.

    However, this pattern will also matches 100% packet loss. I suggest ", 0%% packet loss".

    Also, it won't work in macOS which shows decimals in the report: 0.0% packet loss.