Advertisement
aeberts

Clojure update-in questions

Jan 24th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (def testds {:e [
  2.                 {:c :blah :x 1 :y 2}
  3.                 {:c :foo :x 2 :y 5}]
  4.             :e1 [
  5.                 {:c :blah :x 1 :z 2}
  6.                 {:c :foo :x 5 :z 12}]})
  7.  
  8. repl=> (swap! testds update-in [:e0] conj {:c :zoom :x 1 :y 1})
  9. {:e0 [{:c :blah, :x 1, :y 2} {:c :foo, :x 2, :y 5} {:c :zoom, :x 1, :y 1}], :e1 [{:c :blah, :x 1, :z 2} {:c :foo, :x 5, :z 12}]}
  10. ;; Adding a map to the entity vector works at the repl.
  11.  
  12. (defn create-entity! [state name]
  13.   "adds entity with given name to state atom"
  14.   (swap! state assoc (gensym name) (vector nil)))
  15.  
  16. (defn add-component! [state e m]
  17.   "add given component c to entity e in the game state"
  18.   (let [entity e
  19.         component m]
  20.     (swap! state update-in (vector entity) conj component)))
  21.  
  22. repl=> (create-entity! testds :e4)
  23. {:e0 [{:c :blah, :x 1, :y 2} {:c :foo, :x 2, :y 5}], :e1 [{:c :blah, :x 1, :z 2} {:c :foo, :x 5, :z 12}], :e42 [nil]}
  24. ;; OK, that looks correct
  25.  
  26. repl=> (add-component! testds :e42 {:c :bleck :x 1 :y 2})
  27. {:e0 [{:c :blah, :x 1, :y 2} {:c :foo, :x 2, :y 5}], :e1 [{:c :blah, :x 1, :z 2} {:c :foo, :x 5, :z 12}], :e42 [nil], :e42 ({:c :bleck, :x 1, :y 2})}
  28. ;; But when using add-component! it appends a new entity vs adding a map to the entity vector.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement