forked from svaarala/duktape
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval.c
More file actions
62 lines (50 loc) · 1.25 KB
/
Copy patheval.c
File metadata and controls
62 lines (50 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* Very simple example program for evaluating expressions from
* command line
*/
#include "duktape.h"
#include <stdio.h>
static duk_ret_t native_print(duk_context *ctx) {
duk_push_string(ctx, " ");
duk_insert(ctx, 0);
duk_join(ctx, duk_get_top(ctx) - 1);
printf("%s\n", duk_to_string(ctx, -1));
return 0;
}
static duk_ret_t eval_raw(duk_context *ctx, void *udata) {
(void) udata;
duk_eval(ctx);
return 1;
}
static duk_ret_t tostring_raw(duk_context *ctx, void *udata) {
(void) udata;
duk_to_string(ctx, -1);
return 1;
}
static void usage_exit(void) {
fprintf(stderr, "Usage: eval <expression> [<expression>] ...\n");
fflush(stderr);
exit(1);
}
int main(int argc, char *argv[]) {
duk_context *ctx;
int i;
const char *res;
if (argc < 2) {
usage_exit();
}
ctx = duk_create_heap_default();
duk_push_c_function(ctx, native_print, DUK_VARARGS);
duk_put_global_string(ctx, "print");
for (i = 1; i < argc; i++) {
printf("=== eval: '%s' ===\n", argv[i]);
duk_push_string(ctx, argv[i]);
duk_safe_call(ctx, eval_raw, NULL, 1 /*nargs*/, 1 /*nrets*/);
duk_safe_call(ctx, tostring_raw, NULL, 1 /*nargs*/, 1 /*nrets*/);
res = duk_get_string(ctx, -1);
printf("%s\n", res ? res : "null");
duk_pop(ctx);
}
duk_destroy_heap(ctx);
return 0;
}