lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 8-Feb-07, at 12:23 AM, Glenn Maynard wrote:

On Wed, Feb 07, 2007 at 08:35:43PM -0800, gary ng wrote:
I want to write lua modules and put some self testing
code at the end of the script which got executed only
if it is run as its own and not through "require".

In python, this is usually done through

if __name__ = "__main__":

How should I do it in lua ?

I'm not sure (Rici probably answered that), but for this particular
task, I'd probably do it a little differently:

lua -e 'RunTests = true;' YourScript.lua

and then check RunTests.

Well, in casting about for a way to simulate the Pythonic
behaviour, I did consider that, but the problem is that if
all of your modules use that system, and the target module
require()s another module, then both modules will self-test,
which may not be what you wanted (particularly if the
self-tests take a long time and/or there are a lot of
dependencies.)

So you could modify that slightly by setting
    RunTests = "modulename"
instead of just to true. However, that means hard-coding
the name of the module into the module-file, which I
wanted to avoid.

So what I was looking for was a way for a module to tell
fairly definitively whether it had been require()'d or
dofile()'d; checking the package.loaded table for a
magic undocumented sentinel may not be the most pleasant
solution, but it works. Your mileage and aesthetic sensibilities
may vary. :)