Leo
Leo

Reputation: 1934

Sharing Lisp symbols across packages

I have a function foo defined in a package my-package:

(in-package :my-package)
(defun foo (a)
  (if (eql a 'value1)
    (do-this)
    (do-the-other)))

When I call this function from a different package I have to qualify the parameter with the package name:

(in-package :cl-user)
(my-package:foo 'my-package::value1)

but this is rather ugly. I want to share the symbol value1 with all other packages. I found one workaround which is to import the symbol value1, but this only works if it has been already defined in the other package. Another possibility is to pass strings, "value1", but again, this is just a patch. What is the best way to share symbols across packages? Thanks for your help.

Upvotes: 1

Views: 121

Answers (1)

Rainer Joswig
Rainer Joswig

Reputation: 139251

Use a keyword symbol, which you can always write without naming its package keyword:

(foo:bar :value1)

Keyword symbols are in the KEYWORD package, are evaluating to themselves, are automatically exported and you don't need to write down the package name.

Since a keyword symbol evaluates to itself, you even don't have to quote them - but you can.

(foo:bar ':value1)

Alternative: short package names

Sometimes it might be useful to have a symbol in a specific package. Then I would use a short package name, which you can also define as a nickname. See the options on DEFPACKAGE. For example the package color-graphics could have the nickname cg.

Then one would write:

(foo:bar 'cg:green)

Since it is a normal symbol, you have to quote it, otherwise it would be a variable.

Upvotes: 4

Related Questions