tonumber

From ComputerCraft
Jump to: navigation, search

tonumber
Function
Syntax
tonumber()
Returns number | nil
API Base globals
Source Lua (source)

Parses a number contained in a string. Useful for retrieving numeric values from user input. If str cannot be parsed as a number, the function will return nil.

ExampleExampleAdd 5 to a number entered by the user
Prompt the user for a number, then increment it by 5 and print the result.
Code
local num = tonumber(read())
if num == nil then
    printError("Please enter a number!")
else
    print(num + 5)
end
Output If the user did not enter a valid number, the program will print "Please enter a number!". If the user did enter a valid number, it will print its value + 5.