Evaluating expressions contained as strings
Asked Answered
T

2

11

I've a database which returns vaild CL expressions within double quotes.

Is it possible to convert these strings to expressions.

For example, I make a query from this DB via CLSQL and as a result it returns me:

"(foo a b)"

How should I convert this expression to:

(foo a b)

and further evaluate it?

Throwback answered 30/9, 2011 at 14:41 Comment(0)
A
16
> (read-from-string "(foo a b)")
(FOO A B) ;
9

The 9 is the second of multiple values produced by read-from-string; you can ignore it:

(eval (read-from-string "(foo a b)"))

will do what you want given the proper definitions.

Anticlockwise answered 30/9, 2011 at 14:47 Comment(1)
Thanks, how can i could not find that function?Throwback
S
4
* (read-from-string "(+ 1 2)")

(+ 1 2)
7

There is a security problem. See the variable *read-eval*.

* (read-from-string "#.(+ 1 2)")

3
9

You really need to make sure that *read-eval* is NIL, so that reading will not evaluate code.

* (let ((*read-eval* nil)) (read-from-string "#.(+ 1 2)"))

debugger invoked on a SB-INT:SIMPLE-READER-ERROR:
  can't read #. while *READ-EVAL* is NIL

Additionally calling EVAL on arbitrary input from a database is not a good idea.

Usually you want to make sure that the code does only call allowed functions.

Suggestive answered 31/10, 2013 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.