Quirrel4.41.0

iostream.stream.readobject

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

Deserializes an object from the stream

Parameters

classestable|nulla table from class name to class, needed only when the data contains an instance optional

Return value

The value writeobject encoded: null, a bool, an int, a float, a string, an array, a table, or an instance of a class named in classes. Building an instance calls that class's constructor and then its __setstate method with the saved state.

Errors

Throws Unexpected end of data during deserialization when the stream runs out of bytes before a complete value has been read, including when nothing is left, and Invalid start marker during deserialization or Invalid end marker during deserialization when the bytes at the cursor are not what writeobject produces, for example a stream not created by it, or one read from the wrong position.

An instance in the data needs classes to resolve it, and that class needs a __setstate method to receive the saved state:

Notes

The same method works on a file. Pairing writeobject and readobject on the same stream round-trips a value, provided classes lists every class either side needs; see iostream.stream.writeobject for what it can encode.

Example

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

let b = blob(0)
b.writeobject(42)
b.seek(0)
println("b.readobject() =", b.readobject()) // 42

let empty = blob(0)
try { empty.readobject() } catch (e) { println("empty.readobject() throws:", e) } // nothing was ever written

class Point { function __getstate() { return 1 } function __setstate(s) {} }
let b2 = blob(0)
b2.writeobject(Point(), {Point=Point})
b2.seek(0)
try { b2.readobject() } catch (e) { println("b2.readobject() throws:", e) } // classes omitted this time
Output:
b.readobject() = 42
empty.readobject() throws: Unexpected end of data during deserialization
b2.readobject() throws: Instance found during deserialization, but available classes not set or not a table

See also

readobjectDeserializes an object from the stream
writeobjectSerializes the object to the stream
readblobReads up to size bytes and returns them as a blob
streamclass index