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 end -- or string['capitalize'] = function(self) -- body goes here end
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:
- String: A function for splitting strings
- String: Which string conversion should I use, S() or nodeValue()?
- XML Node: Helper function for getting text between XML tags like <Name>Fred</Name>
- Node: Method to see if a node has a member with a given name
- Node: Specify the minimum number of fields in an HL7 segment
- Node: Formatting output HL7 without trailing | characters
- Node: Helper function which uses the grammar information of the HL7 node tree
- DB Node: Dealing with NULL data from databases, uses
node.presentButNull()to customize treatment of NULL values
- We also supply modules containing multiple extension functions