No. Lua has no way to tell if a script is being invoked "directly".
Remember: Lua and Python exist for different purposes. Python is designed for command-line scripting. You write a script, which calls modules that may be written in Python, C++, or whatever. The Python script is ultimately what is in charge of which code gets called when.
Lua is an embedded scripting language, first and foremost. While you can certainly use the standalone lua.exe
interpreter to create command-line scripts, that is something of a kludge. The language's primary purpose is to be embedded in some application written in C, C++, or whatever.
Because of this, there is no concept of a "main" script. How would you define what is "main" and what is not? If C code can load any script at any time, for any purpose, which one of them is "main"?
If you want to define this concept, it's fairly simple. Just stick this at the top of your "main" script:
do
local old_dofile = dofile
function new_dofile(...)
if(__is_main) then
__is_main = __is_main + 1
else
__is_main = 1
end
old_dofile(...)
__is_main = __is_main - 1
if(__is_main == 0) then __is_main = nil end
end
dofile = new_dofile
end
Granted, this won't work for anything loaded with require
; you'd need to write a version of this for require
as well. And it certainly won't work if external code uses the C-API loading functions (which is why require
probably won't work).