Difference between revisions of "Tonumber"

From ComputerCraft Wiki
Jump to: navigation, search
m
m (Expanded)
 
(One intermediate revision by one other user not shown)
Line 2: Line 2:
 
{{Function
 
{{Function
 
|name=tonumber
 
|name=tonumber
|args=[[string (type)|string]] to be converted into a number (needs to be a number)
+
|args={{type|string}} number [<nowiki/>, {{type|number}} base]
 +
|returns=None
 
|addon=ComputerCraft
 
|addon=ComputerCraft
|desc=Converts a string into a number  
+
|desc=Tries to convert its argument to a {{type|number}}. If the argument is already a number or a string convertible to a number, then '''tonumber''' returns this number; otherwise, it returns {{type|nil}}.<br><br>
 +
 
 +
An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.
 
|api=
 
|api=
 
|examples=
 
|examples=
 
{{Example
 
{{Example
|desc=Converts the strings into numbers and adds the together. (It would be more intelligent to just save it as a number.)
+
|desc=Converts strings into numbers and adds them together. (It would be more intelligent to just save it as a number.)
|code=number1 = "10"
+
|code=local number1 = "10"
  number2 = "5"
+
  local number2 = "5"
  print (number1, " + ", number2, " = ", tonumber (number1) + tonumber (number2))
+
   
 +
[[print]](number1, " + ", number2, " = ", '''tonumber(number1)''' + '''tonumber(number2)''')
 
|output = 10 + 5 = 15
 
|output = 10 + 5 = 15
|notes=*
 
 
}}
 
}}
 
}}
 
}}
 +
 +
[[Category:Lua_Core_Functions]]

Latest revision as of 18:41, 10 April 2014


Grid Redstone.png  Function tonumber
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.

An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.
Syntax tonumber(string number [, number base])
Returns None
Part of ComputerCraft
API none

Examples

Grid paper.png  Example
Converts strings into numbers and adds them together. (It would be more intelligent to just save it as a number.)
Code
local number1 = "10"
local number2 = "5"

print(number1, " + ", number2, " = ", tonumber(number1) + tonumber(number2))
Output 10 + 5 = 15