Quirrel4.41.0

iostream.blob.readn

Method of blob, from module "iostream"
instance.readn(format: int): number

Reads a value of the given numeric format and returns it

examples/iostream/blob/readn-basic.nut
from "iostream" import blob

let ammo = blob(0)
ammo.writen(200, 'i')
ammo.seek(0)
println("ammo.readn('i') =", ammo.readn('i'))
Output:
ammo.readn('i') = 200

Parameters

formatinta character selecting the type and size to read

Return value

See iostream.stream.readn for the format codes, their sizes and the byte order used.

Errors

Throws io error when fewer bytes than the format needs are left before len.

Notes

This is not the same as indexing with blob[i]: indexing reads a single raw byte at an absolute position, does not move the cursor, and applies no numeric conversion, while readn converts a fixed number of bytes starting at the cursor and advances it by that many bytes.

Example

examples/iostream/blob/readn.nut
from "iostream" import blob

let b = blob(0)
// one byte at a time, so the printed values cannot depend on byte order
b.writen(0x41, 'b')
b.writen(0x42, 'b')
b.seek(0)

println("b.readn('b') =", b.readn('b'))   // readn converts and moves the cursor
println("b.tell() after readn('b') =", b.tell())

println("b[1] =", b[1])           // indexing reads a byte but never moves the cursor
println("b.tell() after b[1] =", b.tell())

b.seek(1)               // only 1 byte remains, readn('i') needs 4
try {
  b.readn('i')
} catch (e) {
  println("b.readn('i') throws:", e)
}
Output:
b.readn('b') = 65
b.tell() after readn('b') = 1
b[1] = 66
b.tell() after b[1] = 1
b.readn('i') throws: io error

See also

readnReads a value of the given numeric format and returns it
writenWrites a numeric value in the given format
seekSeeks to the given offset; origin is 'b' (begin), 'c' (current) or 'e' (end)
blobclass index