-
Notifications
You must be signed in to change notification settings - Fork 8
3.3 Use LispE in your C programs
Claude Roux edited this page Nov 26, 2020
·
1 revision
In fact, it is possible to create and call a LispE interpreter from a C++ program. All you need to do is to link with the liblispe.a library created in the bin directory along with the executable.
The operation takes only a few lines of code:
#include "lispe.h"
//We create a LispE interpreter
LispE* lisp = new LispE;
// Loading and executing a LispE program
Element* e = lisp->load(filename);
//The result is displayed
cout << e->toString(lisp) << endl;
//We get rid of the object
e->release();
delete lisp;
If you have the code in the form of a string, it is also possible to use:
Element* e = lisp->execute("(cons 'a ())");
//The result is displayed
cout << e->toString(lisp) << endl;
//We get rid of the object
e->release();
Note the use of toString, which returns a std::string object that can be displayed on screen. The internal Unicode std::wstring are then converted into UTF8 strings on the fly.
For example, here is the simplest LispE interpreter you can create:
int main(int argc, char *argv[]) {
LispE lisp;
//loading a file and executing it
if (argc == 2) {
string file = argv[1];
Element* e = lisp.load(file);
std::cout << e->toString(&lisp) << std::endl;
e->release();
return 0;
}
string code;
//keyboard reading of a LispE expression and evaluation on the fly
cout << endl < "Lisp Elementary (" << version << ")" << endl << endl;
std::cout << "> ";
while (getline(std::cin, code)) {
s_trim(code);
//if it's not a LispE expression, we create a call to 'print'; //if it's not a LispE expression, we create a call to 'print'.
//In this way, you can display the content of a variable
if (code [0] != '(' && code.back() != ')') {
code = "(print" + code + ")";
}
Element* e = lisp.execute(code);
std::cout << e->toString(&lisp) << std::endl;
e->release();
code = "";
std::cout << "> ";
}
}