lua-users home
lua-l archive

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


2014-09-21 4:45 GMT+02:00 Ashish Ranjan <ashishwave@yahoo.com>:
> FEATURE REQUEST: In python , we have a construct
>         if __name__ == “__main__”:
> so that if a module .lua file is executed by itself then this code block
> executes, but if this module is imported(required() as in lua) by other
> script file, then this code blosk is not executed.
> Can we have this construct in lua. This will be an important step in life of
> a lua module.
>
> Kindly see for better explanation http://stackoverflow.com/a/20158605

Before I get to your topic, please note that your mail configuration
produces an X-Spam score of 7.2 which is likely to trigger the Spam
filter of many mail clients, including default settings on gmail.

There are many ways to test something of the kind. None of them
does exactly what you want, since Lua does not have __name__,
but maybe some of them could answer you purpose.

One rather easy-to-understand way is to test debug.traceback().
I've made a file ./snoopy.lua containing one line:
   print(debug.traceback())

I get the following output:

$ lua ./snoopy.lua
stack traceback:
    ./snoopy.lua:1: in main chunk
    [C]: in ?
$ lua -e "require 'snoopy'"
stack traceback:
    ./snoopy.lua:1: in main chunk
    [C]: in function 'require'
    (command line):1: in main chunk
    [C]: in ?
$ lua -e "dofile 'snoopy.lua'"
stack traceback:
    snoopy.lua:1: in main chunk
    [C]: in function 'dofile'
    (command line):1: in main chunk
    [C]: in ?

They're different, allowing you to test inside 'snoopy.lua'.