Tostr

From Pico-8 Wiki
Jump to navigation Jump to search
tostr( val, [format_flags] )
Converts a non-string value to a string representation.
val
The value to convert.

format_flags
Bitfield which allows different operations to occur in the conversion

Returns the string representation of the value.

Given a number value, tostr() returns a string of the signed decimal representation of the number. If you set the optional second parameter to true (or 1), it will return an unsigned fixed point hexadecimal representation. (Use sub() on the result if you only want a portion of this string.)

Given a non-number value type, tostr() attempts to return something useful. Passing in a Boolean returns 'true' or 'false'. Passing in a string returns the string. nil, tables, functions, and threads return [nil], [table], [function], and [thread], respectively.

This is especially useful when concatenating values into string messages. The string concatenation operator (..) only accepts a string or a number on the right-hand side. A value of any other type must be converted to a string with tostr() before being concatenated to a string.

[format_flags] is a bitfield:

  0x1: For numbers, return a string with their full unsigned hexadecimal value (like '0x0012.8400')
       For tables and functions, return a string that uniquely identifies this object (e.g. 'table: 0x1234567')
  0x2: For numbers, return a string with a signed 32-bit integer by shifting the number left by 16 bits.

Examples

s = 'v: '..tostr(12345)            -- 'v: 12345'
s = 'v: '..tostr(-12345.67)        -- 'v: -12345.67'

s = 'v: '..tostr(0x0f)             -- 'v: 15'
s = 'v: '..tostr(0x0f, true)       -- 'v: 0x000f.0000'
s = 'v: '..tostr(-12345.67, true)  -- 'v: 0xcfc6.547b'

s = 'v: '..sub(tostr(0x0f, 3, 6))  == 'v: 000f'

-- runtime error: attempt to concatenate a boolean value
s = 'v: '..true                    

s = 'v: '..tostr(true)             -- 'v: true'
s = 'v: '..tostr('my string')      -- 'v: my string'

s = 'v: '..tostr(nil)              -- 'v: [nil]'
s = 'v: '..tostr({1, 2, 3})        -- 'v: [table]'

f = function() print('hi') end
s = 'v: '..tostr(f)                -- 'v: [function]'

-- f is a function that does not return a value
f = function() return end
a = 'v: '..tostr(f())              -- 'v: [no value]'

See also