lua

How to check if value is string in lua?


Hello guys i please need your help. I have values, most of them are numbers but some of them are strings. How can i check if value is string or number?

I already tried this code but when it reach string value i get error " attempt to perform arithmetic on local 'numberValue' (a nil value)"

function Config:IsNumber(value)
    if value ~=nill or value ~=nil then                 
        local numberValue = tonumber(value)
        if numberValue/numberValue ==1 then
            return true
        else
            return false
        end
    end
end
end
end

Solution

  • First of all let's start with errors in your code.

    Other issues / things to improve:

    numberValue / numberValue == 1 does not make any sense. A number divided by itself always results in 1. So checking that is pointless.

    Also instead of

    if something == 1 then
      return true
    else
      return false
    end
    

    Can simply be replaced by return something == 1. There is no need for a conditional statement here.

    To your question:

    To check wether a value is a string use type(value) == "string".

    To check wether a value can be converted to a number use tonumber(value). It will either return a number or nil.

    So according to your error the conversion to a number failed.

    If you don't know for sure that your value can be converted to a number, you should ensure that tonumber succeeded before you do any operations on its return value.

    local numberValue = tonumber(value)
    if not numberValue then
      print("converting value to a number failed")
      return
    end
    -- at this point you know numberValue is a number
    

    So if you wanted to write a function that ensures a string represents a number you could do something like this:

    function IsNumber(value)
      return tonumber(value) and true or false
    end