util.serialization
Often you will find yourself wanting to convert a table of data to a string. You would need to do this before saving to a file, or displaying on-screen for example.
This serialization library provides that functionality.
Many different types can be serialized, though some are not supported (some are not possible, others may just need adding). The following is a list of types:
Supported | number, string, boolean, table |
Not supported | function |
Stanza objects consist of tables and so can be serialized, but currently some extra steps are necessary.
Reference
serialize(data)
Returns a string representing the given data (usually, but not always, a table).
deserialize(string)
Returns the original data, given a string returned by serialize(data).
append(object, data)
Deprecated and removed in 0.12.0.
Appends the string data to 'object', which may be any object with a 'write' method (such as a file, or socket), otherwise it is assumed to be an array and the data is inserted at the end of the array.
new(options)
Added in 0.12.0.
Configures and returns a custom serialize function. The
options
argument is either a string or a table. If it is a
string, it is treated as a preset option.
Basic options
preset
-
String.
"debug"
,"oneline"
or"compact"
. fatal
-
Boolean.
true
for a throwing an error when encountering data that can’t be serialized,false
for inserting a fallback string into the output.
Advanced options
keywords
- Set of keywords. Prevents these from being used as table keys. Defaults to all known Lua keywords as of Lua 5.3.
unquoted
-
A pattern matching table keys that are safe to use without quotes.
Default:
"^[%a_][%w_]*$"
hex
- Prefix for hex-encoded strings. If set, allows large binary strings to be generated in hex form. A hex-decoding function with the same name as the option must be available in the environment when deserializing.
freeze
-
Set to
true
to enable use of metatable__freeze
methods to pre-process table values. Metatable__name
is used as prefix. maxdepth
- Limit on how deeply nested structures may be, 127 by default.
multiref
-
Set to
true
to allow multiple references to the same table. Disabled by default. Cycles are always rejected.
Substrings
These can be tweaked to adjust indentation and spacing and other in-between substrings. Recommended to use presets instead.
Listing with defaults:
indentwith
-
"\t"
itemstart
-
"\n"
itemsep
-
";"
itemlast
-
";\n"
tstart
-
"{"
tend
-
"}"
kstart
-
"["
kend
-
"]"
equals
-
" = "
serialize(data, options)
Allows serializing with options without going through
new()
.