srcnalt / moppu

Autumn Lisp Game Jam 2019 Entry, Pixel Art Platformer Game
11 stars 1 forks source link

local variables #2

Open lispm opened 5 years ago

lispm commented 5 years ago

small improvement to your code: in Common Lisp setting a variable is a different operation from defining it.

(defun check-collision-all (item)
  (setf collides nil)
  (loop
    :for elem :in (nth (- *game-state* 2) *levels*)
    :when (check-collision item elem)
    :do (setf collides t))
  collides)

You have that pattern in your code elsewhere, too. load-level and check-collision for example.

SETF does not define a variable, but sets it only. To define a function local variable one has two options: let and (not that often seen) &aux:

(let ((collides nil))
  (loop ... (setf collides t) ...)
  collides)

or

(defun check-collision-all (item &aux (collides nil))
   (loop ... (setf collides t) ...)
   collides)

Otherwise collides possibly would be a global and undefined variable. A Common Lisp compiler will typically warn about that.

srcnalt commented 5 years ago

Thank you for the info. Indeed I was getting quite many warning messages however did not really know the cause. Soon I will refactor with this info.