calog/examples/embed.c
2026-06-30 20:55:01 -05:00

42 lines
1.4 KiB
C

// examples/embed.c -- add scripting to a C program with calog, in ~30 lines.
//
// The entire embedding surface is calog.h: create a runtime, register a native C
// function the host provides, create a script context on an engine that exposes it,
// and run a script that calls back into the host. Swap calogJsEngine for
// calogLuaEngine / calogSquirrelEngine to change languages -- nothing else changes.
#include "calog.h"
#include <stdio.h>
// A host-provided native, callable from any embedded engine: hostLog(message).
static int32_t hostLog(CalogValueT *args, int32_t argCount, CalogValueT *result, void *userData) {
(void)userData;
calogValueNil(result);
if (argCount != 1 || args[0].type != calogStringE) {
return calogFail(result, calogErrArgE, "hostLog expects one string");
}
printf("[host] %s\n", args[0].as.s.bytes);
return calogOkE;
}
int main(void) {
CalogT *calog;
CalogContextT *ctx;
CalogValueT result;
const char *expose[] = { "hostLog" };
CalogConfigT config = { expose, 1 };
calog = calogCreate();
calogRegister(calog, "hostLog", hostLog, NULL, 0);
calogContextCreate(calog, &calogJsEngine, &config, &ctx);
calogContextStart(ctx);
calogContextEval(ctx, "hostLog('hello from JavaScript, ' + (6 * 7))", &result);
calogValueFree(&result);
calogContextDestroy(ctx);
calogDestroy(calog);
return 0;
}