April 15th, 2010

Convenience features, part 2

A few more convenience-oriented features for the next release...

- You'll be able to use << >> expression in single-quoted strings.  This does the logical analog to what it does for d-strings: it builds a concatenation expression that's evaluated when you evaluate the string.  For example, 'You are in <<me.location.name>>.' effectively turns into the expression 'You are in ' + me.location.name + '.'.

The thing that made it a no-brainer to add this was that I ran into a bug in the compiler where it was already interpreting << sequences in s-strings.  This always led to an error, which means it was in the past basically impossible to write s-strings in that notation, which means there is no compatibility danger with the new syntax.

- There's new syntax for optional arguments.  If you define a function or method like this:

   func(a, b?, c?) { return a+b+c; }

it means that 'a' is required, but 'b' and 'c' are optional: you can call this as func(1), func(1,2), or func(1,2,3).  If you leave out b and/or c, they get default values of nil (but you can also check argcount to see whether they're nil because they were missing or because they were explicitly specified as nil).  If you want to specify a default other than nil, use this syntax:

  func(a, b=2, c=3) { return a+b+c; }

You could formerly get a similar effect with "..." functions, but this is more convenient for cases where you have a fixed number of optional arguments, because it gives the extra arguments names, and it checks that you haven't specified too many arguments.

- New short-hand syntax lets you define a pre-populated lookup table very quickly and easily.  The syntax is based on the regular list syntax, but rather than just giving a list of elements, you give a list of key/value pairs:

  local tab = ['one' -> 1, 'two' -> 2, 'three' -> 3];

- A couple of String improvements.  The new splice() method does fairly complex edits in one go, by replacing a substring with a new substring.  You can append nil to a string and get back the same string.