Tonum

From Pico-8 Wiki
Jump to navigation Jump to search
tonum( val, [format_flags] )
Converts a string representation of a decimal, hexadecimal, or binary number to a number value.
val
Value to be converted; usually a string though numbers are acceptable.

[format_flags]
Bitfield which allows different operations to occur in the conversion.

Returns the number, or no value (effectively nil) if the string does not represent a number. The tonum() function accepts string representations of all number formats supported by PICO-8 (decimal, hexadecimal with 0x prefix, binary with 0b prefix). If the string represents a number outside of the range of PICO-8 numbers, it wraps the number to the range before returning

Additionally, if val is true or false, Returns 1 or 0 respectively (thus allowing to convert booleans to numbers too).

 0x1: Read the string as written in (unsigned, integer) hexadecimal notation without the "0x" prefix
      Non-hexadecimal characters are taken to be '0'.
 0x2: Read the string as a signed 32-bit integer, and shift right 16 bits.
      Can be combined with 0x1 to read the string as an unsigned hexadecimal 32-bit integer and shift right 16 bits.
 0x4: When VAL can not be converted to a number, return 0

Notes

(As of PICO-8 v0.1.11d, tonum('xyz') reports that the string can't be parsed as a number by returning no value. In Lua, this is technically distinct from returning nil, though it is coerced to nil when used in an assignment or comparison.)

Examples

x = tonum('12345')      -- 12345
x = tonum('-12345.67')  -- -12345.67

x = tonum('0x0f')       -- 15
x = tonum('0x0f.abc')   -- 15.6709
x = tonum('0b1001')     -- 9

x = tonum('32767')      -- 32767
x = tonum('99999')      -- -32768
x = tonum('xyz')        -- nil

-- Examples with bitfield

tonum("ff",       0x1)  -- 255
tonum("1114112",  0x2)  -- 17
tonum("1234abcd", 0x3)  -- 0x1234.abcd

See also