ccxvii / mujs

An embeddable Javascript interpreter in C.
http://mujs.com/
ISC License
812 stars 98 forks source link

API call match on a string #104

Closed dzonerzy closed 5 years ago

dzonerzy commented 5 years ago

What i'm doing wrong? I thinks it's something related to this variable not being pushed

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

int main(int argc, char **argv) {
  char *res;
  js_State *J = js_newstate(NULL, NULL, JS_STRICT);
  jsB_initjson(J);
  js_newstring(J, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
  if (js_hasproperty(J, -1, "match")) {
    printf("Have match\n");
  }
  js_getproperty(J, -1, "match");
  js_pushstring(J, "A"); // "AAAAAAAAAAAAAAAAA..".match("A");
  if (js_pcall(J, 1)) {
    fprintf(stderr, "An exception occurred in match function\n");
  } else {
    res = js_tostring(J, -1);
    printf("RES: %s\n", res);
  }
  js_freestate(J);
}
ccxvii commented 5 years ago

1) You don't need to call jsB_initjson(). It is not listed in the mujs.h header so you should be getting compiler warnings about that. 2) js_hasproperty pushes the property if it exists, thus you shouldn't call js_getproperty too. Call one or the other, not both. 3) You need to push an appropriate 'this' object.

What your code is doing is the equivalent of: ("AAAA".match).match("A");

Try this instead:

js_newstring(J, "AAAA");
js_getproperty(J, -1, "match");
js_rot2(J); // swap top two elements on the stack
js_pushstring(J, "A");
// The stack now has: [ String.prototype.match, String("AAAA"), "A" ]
if (js_pcall(J, 1))
    printf("ERROR: %s\n", js_trystring(J, -1, "error"));
else
    printf("RESULT: %s\n", js_trystring(J, -1, "error"));

This is not a bug/issue. Please come to the #mupdf IRC channel on FreeNode if you need help in how to use the API, rather than opening new issues here. You are creating unneccessary noise for people watching this project for actual bugs.