How to convert a string to a number in Lua?

1

In Lua, how to convert a value of type string to type number (integer, float, etc.)?

    
asked by anonymous 24.04.2015 / 17:05

1 answer

1

Lua performs automatic conversion between types string and number and vice versa at runtime.

> print(1+"20")
21
> print(1 .. "2")
12

If you want to explicitly number to string , use the tonumber .

> local a = tonumber("999")
999

> local phi = tonumber("1.61803")
1.61803

> print(tonumber("100e20"))
1e+22

Furthermore, it is tonumber accepted base , which can range from 2 to 36 as the second argument.

> print(tonumber("A",16))
10

> print(tonumber("101010",2))
42
    
24.04.2015 / 17:05