Module minser
Data serialization with minification.
This module contains functions to serialize values to strings, and deserialize these strings back to values. It is able to serialize strings, numbers, booleans, nil values, and tables.
Please note that not all tables can be serialized:
- For keys, only strings, numbers, and booleans are supported. For values, tables are supported in addition to the types for keys. An unsupported type will cause dump to return nil.
- Tables containing circular references will cause dump to return nil.
- Tables referenced more than once in the tree will be serialized separately each time, and will result in references to different tables.
If a table has a __minser
metamethod, the method is called passing it the
table itself and a table to cache seen sub-tables. The method should use the
repr function for sub fields, passing it the "seen" table.
The serialized output is a chunk of Lua code yielding comparable values.
The module does its best to generate the most compact code possible.
Tables with consecutive numerical indices starting from 1 ("arrays") are efficiently stored by omitting the key. Numerical indices after the first nil element are output adorned.
local t = { 42, "Hello!", nil, "blah" } print(dump(t)) --> {42,"Hello!",[4]="blah"}
Keys that are considered valid identifiers are output unadorned; other keys
(including reserved words) are serialized as [key]
.
local t = { a=1, ["b"]=2, c=3 } t["true"] = true -- Note that this is just an example; the order of non-array -- fields is random, so they may not appear as shown here. print(serialize(t)) --> {a=1,b=2,c=3,["true"]=true}
A key is a valid identifier if and only if all the following are true:
- It is a string, and is not empty.
- It consists of only letters, digits, or the underscore. Note that since what Lua considers a "letter" or "digit" depends on the locale, we take a shortcut and only take into account ASCII letters and digits.
- It does not begin with a digit.
- It is not a reserved word as listed in the Lexical Conventions section of the manual for Lua 5.3.
The serialization algorithm only inserts a comma if needed, and it doesn't
add any spaces. The serialized data does not contain the return
statement,
so this must be added if needed. The load function provided by this module
takes care of adding it if needed.
Info:
- License: MIT. See LICENSE.md for details.
- Author: Diego MartÃnez https://github.com/kaeza
Functions
dump (...) | Serialize values. |
repr (val, seen) | Serialize a single value. |
load (data, env) | Load serialized data. |
Functions
- dump (...)
-
Serialize values.
Parameters:
Returns:
- repr (val, seen)
-
Serialize a single value.
Parameters:
Returns:
- load (data, env)
-
Load serialized data.
Parameters:
Returns:
- number or nil Number of returned values on success, nil on error.
- any or string First value on success, error message on error.
- any Extra values are returned as extra results.