svaarala / duktape

Duktape - embeddable Javascript engine with a focus on portability and compact footprint
MIT License
5.94k stars 514 forks source link

Custom getters and setters in C/C++ #1963

Open sazlang opened 6 years ago

sazlang commented 6 years ago

Is there any way to bind getter and setter for JS variable from C? Something like that.

int myVariable = 0;

int myVariableGetter() { return myVariable; }
void myVariableSetter(int v) { myVariable = v; }

int main() {
  ...
  duk_bind_getter_for("myVariable", myVariableGetter);
  duk_bind_setter_for("myVariable", myVariableSetter);
  duk_eval_string(ctx, "myVariable = 5;");
}
svaarala commented 6 years ago

Yes, you can use https://duktape.org/api.html#duk_def_prop.

It works similarly to Object.defineProperty() but takes the getter/setter argument via the value stack, see the API documentation for examples.

sazlang commented 6 years ago

Hmm. Thanks. But what about capturing setters/getters for all dynamic properties of JS object?

svaarala commented 6 years ago

What dynamic properties do you mean?

svaarala commented 6 years ago

Do you mean capturing all property accesses, regardless of property name? If so, getters/setters don't allow you to do that, but you can use a Proxy object for that.

sazlang commented 6 years ago

Yes, I mean. I will look for Proxy object.

svaarala commented 6 years ago

There are some Ecmascript-based Proxy examples here: https://wiki.duktape.org/HowtoVirtualProperties.html. The C API call for creating a Proxy is https://duktape.org/api.html#duk_push_proxy if you'd rather initialize the Proxy from C code.

svaarala commented 6 years ago

Proxy is a generic Ecmascript concept so almost any Proxy tutorial should be usable. Duktape doesn't implement all traps yet, but get, set, has, delete are probably what you need and they are implemented.

svaarala commented 6 years ago

@sazlang Any updates or ready to close?