This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Reference a variable

4 posts · 5645 views

Hi,

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:
12
testVar
12

Is there a way to do the above in lisp?

Many thanks.

Michael.

Re: Reference a variable

Hi,

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.

Re: Reference a variable

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
symbol-value
operator. E.g.:
(defparameter test 123)          ; => TEST
(symbol-value (intern "TEST")) ; => 123
intern
in this case is used to convert the string into a symbol. Good luck.

Re: Reference a variable

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