Hi,
Hopefully the following would help you out to comprehend what's going on in codes, if not, then feel free to ask.
Code:
(if ;; if the following expression is valid then proceed to next expression.
(setq ss (ssget "_X" '((0 . "INSERT"))))
(progn ;; progn function is to allow you to have more than one expression as into your example / codes.
(setq i 0)
(while (setq ent (ssname ss i)) ;; you had an extra bracket and what's more importantly, is that you need to
;; check if the entity is valid then entget the object to
;; pass over any error message such "bad argument type: lselsetp nil".
;; (progn <- this progn is not required since while function would take care of all following expressions if the first is equal to True.
(setq layer (cdr (assoc 8 (entget ent))))
(princ layer)
(setq i (+ 1 i))
)
)
) ;; end of IF function.