Object serialization: Difference between revisions
→{{header|TXR}}: New entry.
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
(→{{header|TXR}}: New entry.) |
||
Line 2,463:
close $f
$obj printGreetings</syntaxhighlight>
=={{header|TXR}}==
TXR Lisp has good support for object serialization. The object file format for compiled files (<code>.tlo</code> files) depends on it.
<syntaxhighlight lang="txrlisp">(defstruct shape ()
(pos-x 0.0) (pos-y 0.0))
(defstruct circle (shape)
radius)
(defstruct ellipse (shape)
min-radius maj-radius)
(defvarl shapes (list (new circle radius 3.0)
(new ellipse min-radius 4.0 maj-radius 5.0)))
(put-line "original shapes:")
(prinl shapes)
(file-put "shapes.tl" shapes)
(put-line "dump of shapes.tl file:")
(put-line (file-get-string "shapes.tl"))
(put-line "object list read from file:")
(prinl (file-get "shapes.tl"))</syntaxhighlight>
{{out}}
<pre>original shapes:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))
dump of shapes.tl file:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))
object list read from file:
(#S(circle pos-x 0.0 pos-y 0.0 radius 3.0) #S(ellipse pos-x 0.0 pos-y 0.0 min-radius 4.0 maj-radius 5.0))</pre>
An object can be given a <code>print</code> method which has a Boolean argument whether to print "pretty" (meaning in some nicely formatted form for humans, not necessarily a serial notation readable by machine). A print method can return the <code>:</code> (colon) symbol to indicate that it declines to print; the default implementation should be used. With that it it possible to do
<syntaxhighlight lang="txrlisp">(defstruct shape ()
(pos-x 0.0) (pos-y 0.0))
(defstruct circle (shape)
radius
(:method print (me stream pretty-p)
(if pretty-p
(put-string `#<circle of radius @{me.radius} at coordinates (@{me.pos-x}, @{me.pos-y})>`)
:)))
(let ((circ (new circle radius 5.3)))
(prinl circ) ;; print machine readably
(pprinl circ)) ;; print pretty</syntaxhighlight>
{{out}}
<pre>#S(circle pos-x 0.0 pos-y 0.0 radius 5.3)
#<circle of radius 5.3 at coordinates (0, 0)></pre>
=={{header|Wren}}==
|