Thanks... your explanation was indeed helpful. It now seems to work :-). The
_reference casting_ I used to get the closure capture working seems a bit
awkward. Any suggestions for improvement would be appreciated.
import flatty, std/[exitprocs, os, times]
type
HistoryEntry = string
History = seq[HistoryEntry]
template reference(thing:untyped): untyped = cast[ref thing.type](addr
thing)
proc persistence(history: var History, filename: string) =
proc save(history: ref History, filename: string) =
writeFile(filename, history[].toFlatty)
if fileExists filename: history = filename.readFile.fromFlatty History
let historyRef = history.reference
addExitProc( proc() = save(historyRef, filename) )
proc show(history: History) =
echo "History:"
for entry in history: echo entry
# Example usage
var history: History
history.persistence "history.his"
show history
history.add "Another entry: " & $now() # Add another entry on each run
Run