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.23mynumber2 = 400mystring1 = " This is a noncontible string"mystring2 = "4839"nilvlaue = niltableValue = {2,3,5,"49"};--will return the original numberprint(tonumber(mynumber1))print(tonumber(mynumber2))--will return nil because this is inconvertible stringprint(tonumber(mystring1))--will return the number equivalent of this stringprint(tonumber(mystring2))--returns nill, because data type nil can't convertprint(tonumber(nilvlaue))--converting the whole of the table will failprint(tonumber(tableValue))--converting a particular convertible element worksprint(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 returnsnil. - 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
nilandtablevalues. - Line 26: We target a convertible string element of the
tablevalue declared earlier and convert it using thetonumber()function.