What is the tonumber() function in Lua?

Overview

The tonumber() method in Lua converts the value provided to it into a number. If this argument is a number or a convertible string, the tonumber() function returns the converted number. If it is not a number or a convertible string, it will return nil.

Syntax

tonumber(targetValue)

Paramters

  • targetValue: This is the value that will be converted to a number value. It can be of any data type.

Return value

The function returns the converted number value.

Code

In the code snippet below, we convert some values to a number value using the tonumber() function:

mynumber1 = 231.23
mynumber2 = 400
mystring1 = " This is a noncontible string"
mystring2 = "4839"
nilvlaue = nil
tableValue = {2,3,5,"49"};
--will return the original number
print(tonumber(mynumber1))
print(tonumber(mynumber2))
--will return nil because this is inconvertible string
print(tonumber(mystring1))
--will return the number equivalent of this string
print(tonumber(mystring2))
--returns nill, because data type nil can't convert
print(tonumber(nilvlaue))
--converting the whole of the table will fail
print(tonumber(tableValue))
--converting a particular convertible element works
print(tonumber(tableValue[4]))

Explanation

  • Line 2–7: We declare variables of different types.
  • Lines 10–11: We try to convert number datatypes to a number using the tonumber() function.
  • Line 14: We use the tonumber() method to convert a non-convertible string to a number. This returns nil.
  • Line 17: We use the tonumber() method to convert a convertible string to a number. It returns the converted value, which is now a number.
  • Lines 20–23: We attempt to convert other data types that are not numbers or strings to a number. We try the nil and table values.
  • Line 26: We target a convertible string element of the table value declared earlier and convert it using the tonumber() function.