Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed cmdline example program #65

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/cmdline/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
({
add : function(a, b) { return a + b; },
mul : function(a, b) { return a * b; },
})
30 changes: 12 additions & 18 deletions examples/cmdline/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,34 @@
// 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 <stdio.h>
#include <stdlib.h>
#include <string.h>

#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[]) {
char mem[8192], dump = 0;
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++) {
Expand Down