How to convert a string to a number in Lua?

Asked

Viewed 933 times

1

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

1 answer

1


The Moon performs a automatic conversion among the types string and number and vice versa at execution time.

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

In case you want to convert explicitly one number for a string, use the function tonumber.

> local a = tonumber("999")
999

> local phi = tonumber("1.61803")
1.61803

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

Besides, it is tonumber accepts a groundwork, which can vary between 2 and 36, as a second argument.

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

> print(tonumber("101010",2))
42
  • 1

    The last example does not work in Lua 5.3. It worked by chance in previous versions. tonumber("101010",2) works in all versions. I mean, if you’re going to give a basis, use a string.

  • @lhf corrected!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.