In python, one would usually define a main function, in order to allow the script to be used as module (if needed):
def main():
print(\"Hello world\")
I am going to suggest yet another variation, that seems to work on lua5.1 as well as lua5.2:
function is_main(offset)
return debug.getinfo(4 + (offset or 0)) == nil
end
if is_main() then
print("Main chunk!")
else
print("Library chunk!")
end
If you do not feel like defining an extra function is_main
for this purpose, you can just do:
if debug.getinfo(3) == nil then
print("Main chunk!")
else
print("Library chunk!")
end
if arg ~= nil and arg[0] == string.sub(debug.getinfo(1,'S').source,2) then
print "Main file"
else
print "Library"
end
An explanation:
arg
table, with arg[0]
being the name of the script.debug.getinfo
function returns a table of information describing the function at the level of the stack given by its numbered argument (1 refers to the function calling getinfo
; 0 refers to getinfo
itself). Its second parameter is optional: it specifies which subset of the getinfo fields to retrieve. The 'S' defines Source names.source
field of the table returned by getinfo
for files contains the name of the file the function was defined in, prefixed with an @
. By passing the value of that field to string.sub(...,2)
, we strip that @
. (The short_src
field contains the name without the @
, but that's because it's defined as a "print-friendly" name, and is less safe than stripping source
.)Note that this code uses a debug
function, so in 5.2 you'll have to require debug
to be able to use it.