FANDOM


tostr( val, [usehex] )

Converts a non-string value to a string representation.

val
The value to convert.
usehex
If true, uses 32-bit unsigned fixed point hexadecimal notation for number values. The default is to use concise decimal notation for number values.

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, 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, and functions return [nil], [table], and [function], 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.

Examples Edit

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 Edit