Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Clojure state work?

Tags:

clojure

quil

I know what state is by concept, but I can't understand how it's been implemented in this example: https://github.com/quil/quil/blob/master/examples/gen_art/31_oo_circles.clj

I just simply don't see it. State implementation happens on lines 100, 109, and 137:

98-100:

(defn mouse-released []
  (add-circles (state :circles)))

109:

(set-state! :circles circles*)

135-140:

(defn draw []
  (background 255)
  (let [circles* (state :circles)
        circles (swap! circles* update-circles)]
    (doseq [c circles]
      (draw-circle c))))

What is happening on those lines?

set-state! is a Quil method, its implementation can be found at https://github.com/quil/quil/wiki/set~state%21

like image 966
Ricardo Sanchez Avatar asked May 06 '26 20:05

Ricardo Sanchez


1 Answers

the short answer: it's using an atom defined in applet.clj

It's a function defined in core.clj on line 17 which extracts state information stored as an atom attached to the metadata on the applet. Set state start by finding the atom that stored the current "state" by calling (:state (meta (current-applet)) which extracts the metadata (which is a map) form the applet object, then returns the atom stored in the :state key. It then calls reset! to put a new value in this atom. It gets included by the (:use quil.core) in the ns declaration.

like image 164
Arthur Ulfeldt Avatar answered May 08 '26 11:05

Arthur Ulfeldt