Eliot’s Tips and Tricks

Writing extension functions

This is a very useful part of the language. It is easy to extend the built in libraries with custom methods. Each Lua library is effectively a collection of functions within a Lua table. You can easily add more functions into these tables. Two important tables are called “string” which covers the Lua string library and “node” which covers the node tree objects of the Iguana Translator.

This shows an example that we ship in the stringutil module that extends the string library. Here is its definition and you can see the guts of how it works from the annotations. The sub, upper and lower functions are all part of the standard Lua string library.

We have thus extended the string library and this new method can invoked on any string object in Lua. Here is an example of where we call it:

Because we are in effect adding functions to a Lua table there are alternative syntaxes that could be used:

string.capitalize = function(self)  
   -- body goes here
-- or
string['capitalize'] = function(self) 
   -- body goes here

One common helper routine I like to use frequently is the node.S() routine as defined in the node module that ships with Iguana. Another useful routine is one to see if a node has a member with a given name.

Many useful examples can be found in the wiki:


One Comment

  1. Pingback: Will You Share Your Code? - iNTERFACEWARE Inc.

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.