Check if variable is numeric



Published: 2019-08-11 11:24:11 +0000
Categories: LUA,

Language

LUA

Description

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

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

License

BSD-3-Clause

Keywords

LUA, type checking, integer, number, numeric,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion