cyanogilvie / Tcl.js

Javascript implementation of the Tcl language
Other
157 stars 6 forks source link

Passing objects between Tcl and calling context #1

Closed retorquere closed 8 years ago

retorquere commented 9 years ago

Is it possible to pass objects (with or without methods) between the Tcl interpreter and the calling context?

cyanogilvie commented 9 years ago

For some reason I didn't get an email notification from github, sorry for the delay.

The values passed to and returned from the Tcl interp use a dual-ported scheme closely based on the one used by the C interp (described in the TclNewObj manpage). The core of that subsystem is defined in amd/tclobject.js and specific types are defined in amd/objtype*.js.

I'm not certain what you mean by object, but if you mean a native javascript object then you'd probably have to define a new objtype to teach the interpreter about your type and allow the Tcl scripts to meaningfully interact with the values. Since Tcl is EIAS (Everything Is A String) - all objtypes must have conversions to and from a string rep to the internalRep (implemented in this interpreter as a native javascript value stored in obj.jsval)

If you just want Tcl to be able to access the javascript object like a dictionary, then that is already possible: new DictObj(my_js_object) - the objtype_dict.js will convert a javascript object into a Tcl dict, but since methods in a javascript objects are just functions and function values in javascript are just a type of object, they will just be treated as a dict too.

There is a generic objtype called "jsval" which will just store the javascript value (int, function, whatever) in the internalRep, but if the Tcl script reads the value it will get the string returned by .toString() on the internalRep, and if it writes to it or causes it to shimmer to a different type then the supplied jsval will be overwritten (ie. the Tcl script calls [incr foo] where the foo var contains your jsval).

Can you describe what you want it to do? Then I can be more specific.

retorquere commented 9 years ago

Yup, dictionary would suffice. I can strip methods beforehand. I am looking for a safe way to allow users to add bits of code at the end of processing citations for https://github.com/zotplus/zotero-better-bibtex

cyanogilvie commented 9 years ago

That sounds like a pretty reasonable use case. I added a small example of one way to handle that sort of pattern: https://github.com/cyanogilvie/Tcl.js/blob/master/demos/dsl.js

Another way might be to create a new tcl command to allow the scripts to access fields and call methods in the citation instance, object style:

$citation some_property ;# Would return "some_property" $citation some_method $foo ;# Would call the javascript method "some_method" on the citation instance and return its result