Check if variable is numeric (LUA)

LUA isn't strictly typed, and doesn't have a built-in mechanism for type checking paramaters and variables.

Sometimes, though, we need to check that a value is of a given type - a LUA component of a WAF might, for example, want to check that a specific query-string argument is numeric

This snippet focuses solely on that use-case - checking that a variable/string is numeric in format

Similar To

Details

Snippet

function is_numeric(x)
    if tonumber(x) ~= nil then
        return true
    end
    return false
end

Usage Example

vals = {"1234","abcd",'1a','1.1'}

for _,v in pairs(vals) do
        if is_numeric(v) then
           print("Yes - " .. v)
        else
           print("No - " .. v)
        end
end

-- Output:
-- Yes - 1234
-- No - abcd
-- No - 1a
-- Yes - 1.1