How to convert string to boolean in lua

Viewed 5305

I have data received from another script where the variable has the value "false" or "true". I want to convert this value to true or false in lua datatype. Currently, I can do this long way:

if value == "false" then
  value=false
elseif value == "true" then
  value=true
end

Is there a simplest way to convert this like converting string to integer tonumber("1")

4 Answers

You can also do this:

stringtoboolean={ ["true"]=true, ["false"]=false }
print(stringtoboolean[s])

Since I frequently do the conversion for each data received, manually converting the string to boolean like I posted above will make the code redundant. So I create a function to overcome this:

function toboolean(str)
    local bool = false
    if str == "true" then
        bool = true
    end
    return bool
end

So I can do this

toboolean("true") 

and anything other than the "true" string will become false

No, because "false" will also evaluate to true, so if you want "false" to evaluate to false, you will have to convert it manually.

Case independent way:

function str_to_bool(str)
    if str == nil then
        return false
    end
    return string.lower(str) == 'true'
end
Related