Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to add named variables to a SpiderMonkey context?

22 views
Skip to first unread message

Kent Williams

unread,
Jul 15, 2020, 12:20:44 PM7/15/20
to dev-tech-...@lists.mozilla.org
This seems super-obvious to me but it's a part of using the SpiderMonkey
C++ API I haven't had to use before.

1. How do you add named objects to an interpreter context? Like there
should be functions like

JS_AddNamedObject(JSContext *cx, char *name, JS::HandleObject obj);
JS_AddNamedValue(JSContext *cx, char *name, JS::HandleValue obj);

2. Similarly there should be functions to look up values in the
Interpreter context by name.
JS_GetNamedValue(JSContext *cx, char *name, JS::HandleValue &value);

Am I just missing where this stuff is in the API?


USE CASE: I want replace making assignments by building up a script and
then evaluating it, to doing the assignment directly with C++ api.

It should faster to not parse and execute a script, and it would also
get rid of a bunch of escaping you need to do for JS code to interpret
the value literals properly.

James Stortz

unread,
Jul 15, 2020, 2:32:09 PM7/15/20
to dev-tech-...@lists.mozilla.org
The C++ engine is just the underlying implementation of the JS
paradigm, so, the logic will be the same as your script, but low
level.

1 Create the variable handle
2 Assign it a value (such as object, array, function, string, etc.)
3 Define it on an object (such as the global scope)

You will have to follow these steps to define each and every property
or method.

You can also set flags such as read only, permanent, enumerable, etc.
You can also define prototypes and instantiate objects from those
types instead of just generic objects.

see:

JS::RootedValue and (.setString or .setObject or .setBoolean or ...)

JS_DefineFunction or JS_SetFunction
JS_DefineProperty or JS_SetProperty
JS_DefineElement or JS_SetElement

and:

JSPROP_PERMANENT and ...
JSClass and JSClassOps and JS_InitClass
> _______________________________________________
> dev-tech-js-engine mailing list
> dev-tech-...@lists.mozilla.org
> https://lists.mozilla.org/listinfo/dev-tech-js-engine
>

Steve Fink

unread,
Jul 15, 2020, 4:31:57 PM7/15/20
to dev-tech-...@lists.mozilla.org
Yes, you'll probably want to be defining properties on the global.

Note that from C++, usually you'll want the JS_DefineProperty family of
functions, not JS_SetProperty. Setting a property means looking up the
prototype chain to see where a value is defined, setting its value if it
is found, and otherwise defining the property with default flags.
Defining a property means the much more straightforward "I want property
X on object O, with this value, with these flags". JS_SetProperty is
only useful for emulating a `somevar = somevalue` statement in JS.
0 new messages