Reference a variable

Discussion of Common Lisp

Reference a variable

Postby mdaly » Thu Feb 02, 2017 9:59 am


I am trying to find out if there is a way to access a variable by specifying its name as a string. For example I can do the following in lua:

testVar = 12
local s = "testVar"
print (testVar)
print (s)
print (_G[s])

The answers I get are:

Is there a way to do the above in lisp?

Many thanks.

Posts: 1
Joined: Thu Feb 02, 2017 9:38 am

Re: Reference a variable

Postby nuntius » Mon Feb 06, 2017 8:48 pm


There are multiple ways to do this.

A simple way is to use READ and EVAL.

A more specialized way is to use INTERN and SYMBOL-VALUE.
User avatar
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Reference a variable

Postby tsikov » Tue Feb 07, 2017 5:34 am

Lisp is a so-called "LISP-2" meaning that the function names and the variable names "live" two different namespaces. To access the value of a variable given it's symbol, you can use the
Code: Select all
operator. E.g.:

Code: Select all
(defparameter test 123)          ; => TEST
(symbol-value (intern "TEST")) ; => 123

Code: Select all
in this case is used to convert the string into a symbol. Good luck.
Posts: 1
Joined: Tue Feb 07, 2017 5:30 am

Re: Reference a variable

Postby sylwester » Mon Feb 27, 2017 4:17 pm

Even though it can be done I assume you are doing it wrong if you need it.
If you need a hash table why not use a hash table? It can even take arbitrary types as keys if :test is equal.
I'm the author of two useless languages that uses BF as target machine.
Currently I'm planning a Scheme compiler :p
Posts: 133
Joined: Mon Jul 11, 2011 2:53 pm

Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 11 guests