formatting 90% done; encapsulated everything in the TinyJS namespace, and renamed...
[tinyjs-rewrite.git] / src / main.cpp
blobdd4190a0adc5b16919b1c01bb45d3279fce185be
1 /*
2 * TinyJS
4 * A single-file Javascript-alike engine
6 * Authored By Gordon Williams <gw@pur3.co.uk>
8 * Copyright (C) 2009 Pur3 Ltd
10 * Permission is hereby granted, free of charge, to any person obtaining a copy of
11 * this software and associated documentation files (the "Software"), to deal in
12 * the Software without restriction, including without limitation the rights to
13 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
14 * of the Software, and to permit persons to whom the Software is furnished to do
15 * so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in all
18 * copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 * SOFTWARE.
30 * This is a simple program showing how to use TinyJS
33 #include <assert.h>
34 #include <stdio.h>
35 #include "tinyjs.h"
37 const char *code =
38 "function myfunc(x, y)"
39 "{"
40 "return x + y;"
41 "}"
42 "var a = myfunc(1,2);"
43 "print(a);"
46 void js_print(TinyJS::Variable *v, void *userdata)
48 (void)userdata;
49 printf("> %s\n", v->getParameter("text")->getString().c_str());
52 void js_dump(TinyJS::Variable *v, void *userdata)
54 (void)v;
55 auto js = (TinyJS::Interpreter*)userdata;
56 js->getRoot()->trace("> ");
59 void js_lexer(TinyJS::Variable* v, void* userdata)
65 int main(int argc, char **argv)
67 (void)argc;
68 (void)argv;
69 auto js = new TinyJS::Interpreter();
70 /* add the functions from TinyJS_Functions.cpp */
71 registerFunctions(js);
72 /* Add a native function */
73 js->addNative("function print(text)", &js_print, 0);
74 js->addNative("function dump()", &js_dump, js);
76 * Execute out bit of code - we could call 'evaluate' here if
77 * we wanted something returned
79 js->execute("var lets_quit = 0; function quit() { lets_quit = 1; }");
80 printf(
81 "Interactive mode...\n"
82 "Type quit(); to exit, or print(...); to print something, or dump() to dump the symbol table!"
84 while (js->evaluate("lets_quit") == "0")
86 char buffer[2048];
87 fgets(buffer, sizeof(buffer), stdin);
88 try
90 js->execute(buffer);
92 catch(TinyJS::RuntimeError *e)
94 printf("ERROR: %s\n", e->text.c_str());
97 delete js;
98 return 0;