In Lua, how to convert a value of type string to type number (integer, float, etc.)?
In Lua, how to convert a value of type string to type number (integer, float, etc.)?
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