Skip to content

Instantly share code, notes, and snippets.

@kungfooman
Created May 4, 2017 20:12
Show Gist options
  • Save kungfooman/1c8211e9f1603bc73b67a142c7c6ccdf to your computer and use it in GitHub Desktop.
Save kungfooman/1c8211e9f1603bc73b67a142c7c6ccdf to your computer and use it in GitHub Desktop.
statemachine test
#include <stdio.h>
#include "duktape.h"
duk_ret_t duk_func_log(duk_context *ctx) {
int i;
int n = duk_get_top(ctx); /* #args */
char *res;
for (i = 0; i < n; i++) {
res = (char *)duk_to_string(ctx, i);
printf("%s", res);
}
return 0;
}
int duk_func_file_get_contents(duk_context *ctx) {
const char *filename = duk_to_string(ctx, 0);
FILE *f = NULL;
long len;
char *buf;
size_t got;
if (!filename) {
goto error;
}
f = fopen(filename, "rb");
if (!f) {
printf("Cant open file: %s\n", filename);
printf("cant open file: %s", filename);
goto error;
}
if (fseek(f, 0, SEEK_END) != 0) {
printf("cant seek to end\n");
goto error;
}
len = ftell(f);
if (fseek(f, 0, SEEK_SET) != 0) {
printf("cant seek to start\n");
goto error;
}
//buf = duk_push_fixed_buffer(ctx, (size_t) len);
buf = malloc(len + 1);
got = fread(buf, 1, len, f);
buf[len] = 0;
if (got != (size_t) len) {
printf("cant read content\n");
goto error;
}
fclose(f);
f = NULL;
// convert the fixed buffer to string
//char *ret = (char *) duk_to_string(ctx, -1);
duk_push_string(ctx, buf);
//printf("ret=%s\n", buf); // would print the file contents
free(buf);
return 1;
error:
if (f) {
fclose(f);
}
printf("some error reading file in file_get_contents()\n");
//return DUK_RET_ERROR;
duk_push_undefined(ctx);
return 1;
}
int js_register_function(duk_context *ctx, char *name, int (*func)(duk_context *ctx)) {
duk_push_c_function(ctx, func, DUK_VARARGS);
duk_put_global_string(ctx, name);
return 1;
}
int js_push_global_by_name(duk_context *ctx, char *name) {
// [..., global]
duk_push_global_object(ctx);
// [..., global, prop || undefined]
int function_exists = duk_get_prop_string(ctx, -1, name);
// [..., prop || undefined]
duk_remove(ctx, -2);
return function_exists;
}
int main() {
duk_context *ctx = duk_create_heap_default();
js_register_function(ctx, "log", duk_func_log);
js_register_function(ctx, "file_get_contents", duk_func_file_get_contents);
duk_eval_string(ctx, "eval(file_get_contents('statemachine.js'))");
duk_pop(ctx);
char *fsm =
"var fsm = StateMachine.create({ \n" \
" initial: 'green', \n" \
" events: [ \n" \
" { name: 'warn', from: 'green', to: 'yellow' }, \n" \
" { name: 'panic', from: 'yellow', to: 'red' }, \n" \
" { name: 'calm', from: 'red', to: 'yellow' }, \n" \
" { name: 'clear', from: 'yellow', to: 'green' } \n" \
"]}); \n" \
"str = 'abc\\n'; function callme() { log(str); } \n";
duk_eval_string(ctx, fsm);
duk_pop(ctx);
//duk_eval_string(ctx, "callme();");
//duk_pop(ctx);
js_push_global_by_name(ctx, "callme");
int rc = duk_pcall(ctx, 0);
duk_pop(ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment