'how to nest a C function inside a MuJS object
I needed to extend my C app with a scripting language so I tried MuJS, it's written in simple C, but it lacks documentation about specifics. Digging through the code I couldn't figure out how to do this basic task of creating a simple object with a function inside it.
expected result:
myobject: {
myfn: function () {}
}
I tried this but it resulted in an "uncaught exception".
js_newobject(J);
{
js_newcfunction(J, myfn, "myfn", 2);
js_setproperty(J, -2, "myfn");
}
js_setglobal(J, "myobject");
Solution 1:[1]
As you mentionned it, MuJS is poorly documented. You must consider switching to a better documented and widely used alternatives such as LuaJIT. Look at an example here .
Solution 2:[2]
You're probably doing something else wrong, because the code you wrote should work as expected.
Here's a full example with your code that compiles and runs without errors:
#include <stdio.h>
#include "mujs.h"
void myfn(js_State *J)
{
printf("Hello, world!\n");
}
int main(int argc, char **argv)
{
js_State *J = js_newstate(NULL, NULL, 0);
js_newobject(J);
js_newcfunction(J, myfn, "myfn", 0);
js_setproperty(J, -2, "myfn");
js_setglobal(J, "myobject");
js_dostring(J, "myobject.myfn()");
js_freestate(J);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glk0 |
| Solution 2 | ccxvii |
