ccxvii / mujs

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

Exposing js_tovalue( J, idx)->type in some form would be helpful #135

Closed mulle-nat closed 3 years ago

mulle-nat commented 4 years ago

When dynamically interfacing with JS the long if/else chain of js_isnumber, js_isstring, js_isuserdata etc. become tedious. A switch like this is much nicer:

   switch( js_tovalue( J, idx)->type)
   {
   case JS_TNULL      : ...
   case JS_TBOOLEAN   : ... 
   case JS_TNUMBER    : ...
   case JS_TSHRSTR    : ...
   case JS_TLITSTR    : ...
   case JS_TMEMSTR    : ...
   case JS_TOBJECT    : 
      switch( js_toobject( J, idx)->type)
      {
      case JS_CJSON      : ...  
      case JS_COBJECT    : ...
      case JS_CARRAY     : ...
      case JS_CBOOLEAN   : ...
      case JS_CNUMBER    : ...
      case JS_CSTRING    : ...
      case JS_CFUNCTION  : ...
      case JS_CSCRIPT    : ...
      case JS_CEVAL      : ...
      case JS_CCFUNCTION : ...
      case JS_CERROR     : ...
      case JS_CREGEXP    : ...
      case JS_CDATE      : ...
      case JS_CMATH      : ...
      case JS_CJSON      : ...
      case JS_CARGUMENTS : ...
      case JS_CITERATOR  : ...
      case JS_CUSERDATA  : ...
      }
   }

But neither is js_tovalue nor the case values are part of mujs.h. If something like this was "officially" supported it would be nice.

ccxvii commented 3 years ago

js_tovalue exposes internal pointers, which if used incorrectly can cause crashes since they are garbage collected. The JS_T enum exposes internal types like SHRSTR, LITSTR, and MEMSTR which are not useful distinctions to users of the C api. Likewise with the JS_C internal class enum.

js_typeof returns a string with the type name (like the 'typeof' operator), this is as close as you can get without adding another public enum corresponding to those strings which would only be used for that.

mulle-nat commented 3 years ago

Exposing js_tovalue( J, idx)->type would be helpful, possibly as its own function. I think when I wrote this I was at a point, where I tried to use mujs unmodified. But maybe because of this, it didn't work. So I hacked mujs up for my purposes and this is probably moot for me. I'd guess someone else may run into the same problem though.

ccxvii commented 3 years ago

I just said we do expose the type of a value via js_typeof() -- just not as an enum.

mulle-nat commented 3 years ago

String comparing is tedious and slow.