tonumber
Converts a string (of the given base) to a number
Prototype
n = tonumber (n, base)
Description
Converts n to a number using the optional base (default 10). Base can be from 2 to 36. For bases > 10 the letters a-z (not case sensitive) represent the digits. (eg. F is 15).
For decimal numbers you can supply fractions and exponents. Others should be unsigned.
Returns nil if the number cannot be converted.
For decimal numbers you can supply fractions and exponents. Others should be unsigned.
Returns nil if the number cannot be converted.
print (tonumber ("100100", 2)) --> 36
print (tonumber ("1e5")) --> 100000
print (tonumber ("1EF", 16)) --> 495
You can use tonumber as a quick check if a variable contains something convertable to a number.
print (tonumber ("abc")) --> nil
print (tonumber ("-43")) --> -43
print (tonumber (-43)) --> -43
To see if the variable actually is already a number type, use the "type" function:
print (type ("-43")) --> string
print (type (-43)) --> number
See also bit.tonumber which will handle larger numbers.Lua functions
- assert - Asserts that condition is not nil and not false
- collectgarbage - Collects garbage
- dofile - Executes a Lua file
- error - Raises an error message
- gcinfo - Returns amount of dynamic memory in use
- getfenv - Returns the current environment table
- getmetatable - Returns the metatable for the object
- ipairs - Iterates over a numerically keyed table
- load - Loads a chunk by calling a function repeatedly
- loadfile - Loads a Lua file and parses it
- loadlib - Loads a DLL (obsolete in Lua 5.1)
- loadstring - Compiles a string of Lua code
- module - Creates a Lua module
- next - Returns next key / value pair in a table
- pairs - Traverse all items in a table
- pcall - Calls a function in protected mode
- print - Prints its arguments
- rawequal - Compares two values for equality without invoking metamethods
- rawget - Gets the value of a table item without invoking metamethods
- rawset - Sets the value of a table item without invoking metamethods
- require - Loads a module
- select - Returns items in a list
- setfenv - Sets a function's environment
- setmetatable - Sets the metatable for a table
- tostring - Converts its argument to a string
- type - Returns the type of a variable
- unpack - Unpacks a table into individual items
- xpcall - Calls a function with a custom error handler
Topics
- Lua PCRE regular expression functions
- Lua base functions
- Lua bc (big number) functions
- Lua bit manipulation functions
- Lua coroutine functions
- Lua debug functions
- Lua io functions
- Lua math functions
- Lua os functions
- Lua package functions
- Lua script extensions
- Lua string functions
- Lua syntax
- Lua table functions
- Lua utilities
- Scripting callbacks - plugins
- Scripting