MuJS Examples

A stand-alone interpreter

#include <stdio.h>
#include <mujs.h>

int main(int argc, char **argv)
{
	char line[256];
	js_State *J = js_newstate(NULL, NULL, JS_STRICT);
	while (fgets(line, sizeof line, stdin))
		js_dostring(J, line);
	js_freestate(J);
}

Hello, world!

#include <stdio.h>
#include <mujs.h>

static void hello(js_State *J)
{
	const char *name = js_tostring(J, 1);
	printf("Hello, %s!\n", name);
	js_pushundefined(J);
}

int main(int argc, char **argv)
{
	js_State *J = js_newstate(NULL, NULL, JS_STRICT);

	js_newcfunction(J, hello, 1);
	js_setglobal(J, "hello");

	js_dostring(J, "hello('world');");

	js_freestate(J);
}

Configuration file

js_dofile(J, "config.lua")

js_getglobal(J, "foo");
foo = js_tonumber(J, -1);
js_pop(J, 1);

Object manipulation

// t = { foo: 42, bar: true }

js_newobject(J);
{
	js_pushnumber(J, 42);
	js_setproperty(J, -2, "foo");
	js_pushboolean(J, 1);
	js_setproperty(J, -2, "bar");
}
js_setglobal(J, "t");

Complete userdata example

#include <stdio.h>
#include <mujs.h>

#define TAG "File"

static void new_File(js_State *J)
{
	FILE *file;

	if (js_isundefined(J, 1)) {
		file = stdin;
	} else {
		const char *filename = js_tostring(J, 1);
		file = fopen(filename, "r");
		if (!file)
			js_error(J, "cannot open file: '%s'", filename);
	}

	js_currentfunction(J);
	js_getproperty(J, -1, "prototype");
	js_newuserdata(J, TAG, file);
}

static void File_prototype_readByte(js_State *J)
{
	FILE *file = js_touserdata(J, 0, TAG);
	js_pushnumber(J, getc(file));
}

static void File_prototype_readLine(js_State *J)
{
	char line[256], *s;
	FILE *file = js_touserdata(J, 0, TAG);
	s = fgets(line, sizeof line, file);
	if (s)
		js_pushstring(J, line);
	else
		js_pushnull(J);
}

static void File_prototype_close(js_State *J)
{
	FILE *file = js_touserdata(J, 0, TAG);
	fclose(file);
	js_pushundefined(J);
}

void initfile(js_State *J)
{
	js_getglobal(J, "Object");
	js_getproperty(J, -1, "prototype");	// File.prototype.[[Prototype]] = Object.prototype
	js_newuserdata(J, TAG, stdin);		// File.prototype.[[Userdata]] = stdin
	{
		js_newcfunction(J, File_prototype_readByte, 0);
		js_defproperty(J, -2, "readByte", JS_DONTENUM);

		js_newcfunction(J, File_prototype_readLine, 0);
		js_defproperty(J, -2, "readLine", JS_DONTENUM);

		js_newcfunction(J, File_prototype_close, 0);
		js_defproperty(J, -2, "close", JS_DONTENUM);
	}
	js_newcconstructor(J, new_File, new_File, 1);
	js_defglobal(J, "File", JS_DONTENUM);
}