Quirrel4.41.0

iostream.stream.writeobject

Method of stream, from module "iostream"
instance.writeobject(obj, [classes: table|null])

Serializes the object to the stream

examples/iostream/stream/writeobject-basic.nut
from "iostream" import blob

let squadIds = blob(0)
squadIds.writeobject([101, 102, 103])

squadIds.seek(0)
let back = squadIds.readobject()
println("back[0], back[1], back[2] =", $"{back[0]},{back[1]},{back[2]}")
Output:
back[0], back[1], back[2] = 101,102,103

Parameters

objanythe value to serialize
classestable|nulla table from class name to class, needed only when obj contains an instance optional

Errors

Throws Unsupported object type for serialization for a value writeobject cannot encode: a function, generator, thread, weakref, userdata or userpointer, whether obj is that value itself or it turns up nested inside an array or table.

An instance of a class needs classes to name that class, and the class needs a __getstate method that returns the state to save:

Notes

The same method works on a file. Writing past the current len grows a blob to fit, the same as writen.

iostream.stream.readobject reverses this: pairing the two on the same stream round-trips a value, provided classes lists every class either side needs.

Example

examples/iostream/stream/writeobject.nut
from "iostream" import blob

let b = blob(0)
b.writeobject([1, 2])
println("b.len() =", b.len()) // a start marker, the encoded array, an end marker

class Point { function __getstate() { return 1 } function __setstate(s) {} }
try { b.writeobject(Point()) } catch (e) { println("b.writeobject(Point()) throws:", e) } // no classes table passed

try { b.writeobject(print) } catch (e) { println("b.writeobject(print) throws:", e) } // a function cannot be serialized
Output:
b.len() = 6
b.writeobject(Point()) throws: Unsupported class for serialization
b.writeobject(print) throws: Unsupported object type for serialization

See also

writeobjectSerializes the object to the stream
readobjectDeserializes an object from the stream
writeblobWrites the given blob and returns the number of bytes written
streamclass index