Lua - Convert String to Int



Lua does the implicit conversion or also known as coercion when it notices that you are trying to use a number but wrote a string, then it automatically converts the string into an int, and it is quite useful.

Let’s consider a simple example where I will declare a string variable, and then I will try to do an arithmetic operation on it, then once the Lua compiler infers that we are trying to use the string as an int, it will automatically convert it into an int.

Example - Getting types

Consider the example shown below −

main.lua

-- string variabe
str = "10"
-- print type of string variable
print(type(str))
-- double the number
num = 2 * str
-- print the number
print(num)
-- print the type of number variable
print(type(num))

Output

When we run the above code, we will get the following output−

string
20
number

Now that we know about the automatic conversion (coercion), it's a good idea to learn how to do the conversion explicitly, the first approach is to append a 0 to the string value, and that value will be converted to an integer.

Example - Conversion to Number

Consider the example shown below −

main.lua

-- uncommon method
str = "100"
-- add 0 to string
num = str + 0
-- print type of num as string variable
print(type(num))
-- print value of num variable
print(num)

Output

When we run the above code, we will get the following output−

number
100

The above approach is not a very common one, and it's better to use the library function to convert a string to a number.

Example - Converting String to Number

Consider the example shown below −

main.lua

-- common method
str = "100"
-- convert str to number
num = tonumber(str)
-- print type of num variable as number
print(type(num))
-- print value of num variable
print(num)

Output

When we run the above code, we will get the following output−

number
100
Advertisements