How can I convert a string to an integer in Lua?
I have a string like this:
a = \"10\"
I would like it to be converted to 10, the n
tonumber (e [, base])
tonumber
takes two arguments, first is string which is converted to number and second is base of e
.
Return value tonumber
is in base 10.
If no base
is provided it converts number to base 10.
> a = '101'
> tonumber(a)
101
If base is provided, it converts it to the given base.
> a = '101'
>
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
>
If e
contains invalid character then it returns nil
.
> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
>
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171
I answered considering Lua5.3