lua-users home
lua-l archive

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


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