wolery123
wolery123

Reputation: 35

Common Lisp Packages - How to deal when a package might not be loaded?

Assume a common lisp library user could also have loaded package A, package B or neither. I want to be able to accept objects from either package. Ideally it would just be a case of defining a method on those objects. However, if the packages are not loaded at compile time, trying to do that will generate a Package XYZ does not exist error. I don't want to force users to load both packages, so any suggestions on how I can do conditional calls at runtime?

Upvotes: 2

Views: 459

Answers (1)

RowPJ
RowPJ

Reputation: 529

You could do something similar to the following:

(defun foo (x)
   (cond
      ((find-package :bar) (funcall (find-symbol "x" :bar) x))
      ((find-package :baz) (funcall (find-symbol "y" :baz) x))))

Basically, use find-package and find-symbol to check if the package exists and get the symbol from the package if it does. Then, you can use symbol-function and symbol-value to get the function or value associated with the symbol. In my example, funcall automatically looks up the function associated with the symbol returned by find-symbol, so symbol-function wasn't necessary.

Upvotes: 4

Related Questions