Categories
Computers Lua Programming

lua and require

A cool little feature I just came across with lua is that the require function can be used as part of the actual working code. For instance, an optional piece of functionality can be required based on an option flag. The benefit is unnecessary code is only loaded when it’s wanted.

I just wrote an IMAP4rev1 parser to help with making sure imap commands generated by luaimap are syntactically correct. The idea was to eliminate a potential point of confusion when working with the library. Of course, the checker is pretty green at this stage, so it may give a false negative. But at least is give a starting point to the would be developer.

Typically, I’d just require the module at the top of my code, like so:

local chksyntax = require("parser")

And then the parsing function can be invoked in the usual way.

But in this case, I figured the checker should really be part of the IMAP object that luaimap creates. Then I thought, wouldn’t it be nice if I only loaded the module when syntax checking was desired? That way, after a debug and proving out phase, syntax checking could equally be turned off resulting in fast execution. So I added an options table to the new method and then inserted the following lines of code:

       .
       .
       .
if options then
    if options.syntaxchecking then
        o.__checksyntax = require("parser").parse
    end
end

The other cool thing here is that lua allows for grabbing the parse function reference inside the module. In other words, since require returns a table, I can immediately add the parse element for the assignment without generating a syntax error. This is also because lua treats functions as first class values, so they can be assigned just like other variables.

Now, elsewhere in the IMAP object, I can use the parser like so:

if self.__checksyntax and not self.__checksyntax(cmd) then
    error("I can't in good conscience send this command to the server: "..cmd)
end

Anyway, I thought this a somewhat novel (for me) insight into lua usage, and figured I’d pass it along.

Leave a Reply

Your email address will not be published. Required fields are marked *