From de33a876f6d30656ba6dae3eb60e48c683d0481d Mon Sep 17 00:00:00 2001 From: Ava Rider Date: Wed, 21 Feb 2024 16:23:30 +1300 Subject: [PATCH 1/2] Changed print to require --- examples/cmdline/main.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/examples/cmdline/main.c b/examples/cmdline/main.c index 3e7b88c..ce3be83 100644 --- a/examples/cmdline/main.c +++ b/examples/cmdline/main.c @@ -19,14 +19,15 @@ #include "elk.h" -// Prints all arguments, one by one, delimit by space -static jsval_t js_print(struct js *js, jsval_t *args, int nargs) { - for (int i = 0; i < nargs; i++) { - const char *space = i == 0 ? "" : " "; - printf("%s%s", space, js_str(js, args[i])); - } - putchar('\n'); // Finish by newline - return js_mkundef(); +// Function that loads JS code from a given file. +static jsval_t js_require(struct js *js, jsval_t *args, int nargs) { + if (nargs != 1) return js_mkundef(); + char data[1024]; + char *filename = js_getstr(js, args[0], NULL); + FILE *fp = fopen(filename, "rb"); + if (fp == NULL) return js_mkundef(); + size_t len = fread(data, 1, sizeof(data), fp); + return js_eval(js, data, len); } int main(int argc, char *argv[]) { @@ -34,8 +35,8 @@ int main(int argc, char *argv[]) { struct js *js = js_create(mem, sizeof(mem)); jsval_t res = js_mkundef(); - // Implement `print` function - js_set(js, js_glob(js), "print", js_mkfun(js_print)); + // Implement `require` function + js_set(js, js_glob(js), "require", js_mkfun(js_require)); // Treat every argument as JS expressions. Execute all one by one for (int i = 1; i < argc; i++) { From 6834b8c43a32bdc66550bb02ef1af6b4d3b89cca Mon Sep 17 00:00:00 2001 From: Ava Rider Date: Wed, 21 Feb 2024 16:30:19 +1300 Subject: [PATCH 2/2] Added api.js and fixed compile instructions --- examples/cmdline/api.js | 4 ++++ examples/cmdline/main.c | 9 +-------- 2 files changed, 5 insertions(+), 8 deletions(-) create mode 100644 examples/cmdline/api.js diff --git a/examples/cmdline/api.js b/examples/cmdline/api.js new file mode 100644 index 0000000..a2ab40b --- /dev/null +++ b/examples/cmdline/api.js @@ -0,0 +1,4 @@ +({ + add : function(a, b) { return a + b; }, + mul : function(a, b) { return a * b; }, +}) \ No newline at end of file diff --git a/examples/cmdline/main.c b/examples/cmdline/main.c index ce3be83..e2c76cd 100644 --- a/examples/cmdline/main.c +++ b/examples/cmdline/main.c @@ -2,17 +2,10 @@ // All rights reserved // // Example Elk integration. Demontrates how to implement "require". -// Create file "api.js" with the following content: -// ({ -// add : function(a, b) { return a + b; }, -// mul : function(a, b) { return a * b; }, -// }) -// // Compile main.c and run: -// $ cc main.c ../../elk.c -I../.. -o cli +// $ cc main.c ../../elk.c -I../.. -o cli -DJS_DUMP // $ ./cli 'let math = require("api.js"); math.mul(2,3);' // 6 -// Executed in 0.663 ms. Mem usage is 3% of 8192 bytes. #include #include #include