lua-users home
lua-l archive

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

On 7-Feb-07, at 11:35 PM, 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 don't know if this is how you *should* do it, but it is
how you *can* do it (with thanks to lhf and a discussion
on the #lua irc channel):

During the execution of require, the packages.loaded table
entry for the module is set to a sentinel, in order to
detect circular dependencies. The sentinal is a userdata
object. So, if your module does not return a userdata,
you could establish that you're not running inside a
require by checking:

if type(package.loaded.<modulename>) ~= "userdata" then
  -- run self test

or type(package.loaded["<modulename>"]) if the modulename has dots in it.

However, that means that you need to know the name of the module. Fortunately, if the module is being loaded with require, you'll
receive that as the first parameter.

Putting that together:

----- Module selftest.lua -----

local myname = ...

-- My personal style is not to pollute the global
-- namespace with modules, so this is not quite
-- according to PiL, but it works fine.
local Module = {}
function Module.hello(who)
  print("Hello, "..(who or "whoever you are").."!")

-- Since I'm not creating a global, I have to return the
-- Module table.

if type(package.loaded[myname]) == "userdata" then
  return Module
  print "Testing the selftest module"
  print "The next line should be familiar:"