eval.c 918 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Very simple example program for evaluating expressions from
  3. * command line
  4. */
  5. #include "duktape.h"
  6. #include <stdio.h>
  7. static int eval_raw(duk_context *ctx) {
  8. duk_eval(ctx);
  9. return 1;
  10. }
  11. static int tostring_raw(duk_context *ctx) {
  12. duk_to_string(ctx, -1);
  13. return 1;
  14. }
  15. static void usage_exit(void) {
  16. fprintf(stderr, "Usage: eval <expression> [<expression>] ...\n");
  17. fflush(stderr);
  18. exit(1);
  19. }
  20. int main(int argc, char *argv[]) {
  21. duk_context *ctx;
  22. int i;
  23. const char *res;
  24. if (argc < 2) {
  25. usage_exit();
  26. }
  27. ctx = duk_create_heap_default();
  28. for (i = 1; i < argc; i++) {
  29. printf("=== eval: '%s' ===\n", argv[i]);
  30. duk_push_string(ctx, argv[i]);
  31. duk_safe_call(ctx, eval_raw, 1 /*nargs*/, 1 /*nrets*/);
  32. duk_safe_call(ctx, tostring_raw, 1 /*nargs*/, 1 /*nrets*/);
  33. res = duk_get_string(ctx, -1);
  34. printf("%s\n", res ? res : "null");
  35. duk_pop(ctx);
  36. }
  37. duk_destroy_heap(ctx);
  38. return 0;
  39. }