Page 1 of 1

Reference a variable

Posted: Thu Feb 02, 2017 9:59 am
by mdaly
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

Posted: Mon Feb 06, 2017 8:48 pm
by nuntius
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

Posted: Tue Feb 07, 2017 5:34 am
by tsikov
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

symbol-value
operator. E.g.:

Code: Select all

(defparameter test 123)          ; => TEST
(symbol-value (intern "TEST")) ; => 123

Code: Select all

intern
in this case is used to convert the string into a symbol. Good luck.

Re: Reference a variable

Posted: Mon Feb 27, 2017 4:17 pm
by sylwester
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.