[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Is there a similar way to do if __name__ == '__main__' as in python ?
- From: Bret Victor <bret@...>
- Date: Thu, 8 Feb 2007 06:56:27 +0000 (UTC)
gary ng <garyng2000 <at> yahoo.com> writes:
> 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".
Lua is a lot more mutable than most languages. If you
need "require" to do something fancy, it may be simplest
to simply redefine "require":
local oldRequire = require
function require (...)
local wasInsideRequire = isInsideRequire
isInsideRequire = true
oldRequire(...)
isInsideRequire = wasInsideRequire
end
If you like, you can put this bit of code into its own little
module and require it before you require anything else.
Thereafter, anything that wants to know whether it's been
required just has to check the "isInsideRequire" global variable:
if not isInsideRequire then runUnitTest() end