Main Content

Encapsulating shared code in a Lua module

Archive - Originally posted on "The Horse's Mouth" - 2009-08-13 14:31:02 - Graham Ellis

Have you ever written code like this?

seps = {" "," "," [",'] "','" '," ",' "','" "','"'}

Yes, I have ... in fact, that's code that I wrote on Tuesday during the Lua course; it's an indexed table of the separators used to split down a web access log record that's in the apache httpd combined format.

Am I proud of it?

Not really ... in fact, coding it in front of my delegates, I got it wrong initially and we had to go back and look very carefully at the single and double quotes. BUT once I got it right, it works well enough and there are sufficient comments around for it to be debugged if need be. Having said that, I would rather like to hide it under the carpet, and avoid it tripping up anyone else who stumbles across it.

Firstly - I put the code into a function so that it's lightly wrapped (see here) and can be called / prodded / used without the user being fearful of upsetting the code if he/she cuts and pastes it.

Then, I put the code into a separate module. That's a far heavier wrapping, using a table as a fresh namespace, and leaving only the names of the elements in the table / module / namespace visible to the calling file. The module source code is here and the source of a sample calling program is here