Steven S
Steven S

Reputation: 13

How to check only numbers in value - Lua

I want to make sure players can't put letters or symbols in the value, how do I check if it is a number only?

function seed1()
    ESX.UI.Menu.CloseAll()

    ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'amountseed1', {
        title = 'Shop'
    }, function(data, menu)
        local amount = tostring(data.value)
        if amount == nil then
            ...
        else
            [[What should i put here to check its only contain number ?]]
        end
    end, function(data, menu)
        menu.close()
    end)
end

I can put something like this, but maybe this isn't a good way to do that:

else 
    if amount > 0 and amount < 9999 then 
         ...
    else 
        print('Invalid amount or amount higher than 9999')
    end
end

Upvotes: 1

Views: 1375

Answers (2)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7046

Simply replace tostring with tonumber. This will turn strings into numbers if possible, and return nil if it can't.

Keep in mind: tonumber won't just take the largest valid prefix of a string, so tonumber("20 foo") will return nil and not 20. It also supports all ways to write number literals in Lua, so tonumber("2.3e2") will return 230 and tonumber("0xff") will return 255.

Upvotes: 1

Aki
Aki

Reputation: 2928

Since you only care about the number, there is no need to convert the value to string:

local amount = tostring(data.value)
--             ^^^^^^^^ partially useless

Instead, go for the number right away:

local amount = tonumber(data.value)
if amount == nil then
    -- Not a number
else
    -- A number
end

In the end, remember that tonumber attempts to convert the value to a number and returns nil in case of a failure.

Upvotes: 2

Related Questions