April 4th, 2010

Dynamic features, part 1

I mentioned that one of the themes of the next release will be more dynamic coding features. Here's the first peek at some of the specifics - I'll talk about others in the days ahead.

The TADS object model is already pretty dynamic, in that you can add properties on the fly, change property datatypes, get a list of the properties an object has, etc.  But one piece that's been missing is that you can't add a new method to an object at run-time, or turn a property into a method. Methods are essentially a special type of property - a special datatype, actually - that up to now only the compiler could access.

Well, you'll finally be able to manipulate the method complement of an object, using the new TadsObject mehods getMethod() and setMethod().  (These will apply only to TadsObject objects, so adding a method to, say, a BigNumber will still not be possible.)

The new methods act pretty much like you'd expect.  getMethod() retrieves the code of a method property without invoking the code.  If the method contains a code body, you'll get a function pointer value.  If it's a double-quoted string, you'll get a regular single-quoted string value back.  setMethod() lets you assign a code value to a property, making the property into a method.  The code can be given as a function pointer (including an anonymous function pointer), or as a string value (effectively converting it into a double-quoted string method).

For example:

  desk.setMethod(&afterAction, { : "hello!" });


The question that some people will probably ask about this (and pretty much any other dynamic coding feature) is: why would you want this?  These sorts of dynamic capabilities aren't the sort of thing you'd use all the time, but for certain oddball cases, they can be incredibly powerful.  They're particularly powerful for library and extension writers, because they let you do things that in most languages only the compiler can do.