iostream.stream.writeobject
Serializes the object to the stream
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,103Parameters
obj | any | the value to serialize |
classes | table|null | a 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:
Unsupported class for serialization- the instance's class is not a key inclasses(including whenclasseswas not passed)Instance must have __getstate method for serialization- the class has no__getstateInstance method __getstate must be a closure- the class has a__getstateslot, but it is not callable
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
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 serializedOutput:
b.len() = 6
b.writeobject(Point()) throws: Unsupported class for serialization
b.writeobject(print) throws: Unsupported object type for serializationSee also
writeobject | Serializes the object to the stream |
readobject | Deserializes an object from the stream |
writeblob | Writes the given blob and returns the number of bytes written |
| stream | class index |