lua-users home
lua-l archive

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


Why? This is very useful for adding test code to module for unit testing. You want the code to run when running the library script directly but you do not want to run when 'included' by the main app...

-----Original Message----- From: mniip
Sent: Saturday, April 05, 2014 1:26 PM
To: Lua mailing list
Subject: Re: How to tell if running script directly?

On 04/05/2014 02:16 PM, tonyp@acm.org wrote:
Is there an equivalent for Python's

if __name__ == "__main__":
   main()

in Lua?

For example, something like this?  (If not, is this something that
could be added in the next release?)

if _MAIN then
 ...
end

where _MAIN would be true if the script is run directly, and false if
it is part of require or dofile.

TIA
Tony.

If you're using command-line lua executable, something along the lines of

not debug.getinfo(3)

should work, as if the code is placed in main chunk, 0 would be
debug.getinfo, 1 would be the main chunk, 2 would be the code from
lua.c. 3 would be nonexistent.
It is however very easy to break, f.e if the code is ran via
luaL_dostring and not luaL_loadfile, so, may I ask,

Why do you need to detect this, in first place?