processlines.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* processlines.c */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "duktape.h"
  6. int main(int argc, const char *argv[]) {
  7. duk_context *ctx = NULL;
  8. char line[4096];
  9. char idx;
  10. int ch;
  11. ctx = duk_create_heap_default();
  12. if (!ctx) {
  13. printf("Failed to create a Duktape heap.\n");
  14. exit(1);
  15. }
  16. if (duk_peval_file(ctx, "process.js") != 0) {
  17. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  18. goto finished;
  19. }
  20. duk_pop(ctx); /* ignore result */
  21. memset(line, 0, sizeof(line));
  22. idx = 0;
  23. for (;;) {
  24. if (idx >= sizeof(line)) {
  25. printf("Line too long\n");
  26. exit(1);
  27. }
  28. ch = fgetc(stdin);
  29. if (ch == 0x0a) {
  30. line[idx++] = '\0';
  31. duk_push_global_object(ctx);
  32. duk_get_prop_string(ctx, -1 /*index*/, "processLine");
  33. duk_push_string(ctx, line);
  34. if (duk_pcall(ctx, 1 /*nargs*/) != 0) {
  35. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  36. } else {
  37. printf("%s\n", duk_safe_to_string(ctx, -1));
  38. }
  39. duk_pop(ctx); /* pop result/error */
  40. idx = 0;
  41. } else if (ch == EOF) {
  42. break;
  43. } else {
  44. line[idx++] = (char) ch;
  45. }
  46. }
  47. finished:
  48. duk_destroy_heap(ctx);
  49. exit(0);
  50. }