-
Notifications
You must be signed in to change notification settings - Fork 12
Packing and Unpacking
hazzard993 edited this page Jul 20, 2019
·
1 revision
Lua has string.pack
and string.unpack
to serialize values. Love uses love.data.pack
and love.data.unpack
to do what they do.
When packing and unpacking values it is important to keep track of the formatting string used when packing the values.
These declarations have type guards to prevent the wrong types and formatting string from being used.
let a: number, e: string;
const data = love.data.pack("data", "n1", 1, 2, 3, 4);
[a] = love.data.unpack("n2", data); // ❌ Wrong unpacking format
[e] = love.data.unpack("n1", data); // ❌ Unpacked data is not assignable to a string
[a] = love.data.unpack("n1", data); // ✔
The packed data above can be represented with the following type:
type PackedData = love.data.PackedData<{
format: "n1";
values: [1, 2, 3, 4];
}>;
This can be used as a parameter type to prevent the wrong kinds of unpackable values from being sent to it.
function unpack(packedData: love.data.PackedData<{
format: "n1";
values: [1, 2, 3, 4];
}>) {
love.data.unpack("n1", packedData);
}
unpack(love.data.pack("data", "n1", 1, 2, 3)); // ❌ Expected 4 values to be packed
unpack(love.data.pack("data", "n2", 1, 2, 3, 4)); // ❌ Unsupported formatting
unpack(love.data.pack("data", "n1", 1, 2, 3, 4)); // ✔