如何确定我的代码是否在lua模块中运行? [英] How to determine whether my code is running in a lua module?
问题描述
我正在编写脚本 testmodule.lua
,并希望检查此文件是从另一个脚本导入/请求的还是由 lua testmodule.lua
直接启动的./p>
如果它是通过命令行直接启动的,那么我可以做一些测试或运行一个主要功能,否则只需导出一些功能就什么都不做.
Python有一个 __ name __
语句:
如果__name__ =='__main__':main_entry()
lua中有类似的东西吗?
在单个文件中编写Shell util很有用,该文件可以直接运行并由其他lua脚本导入.但是当某些脚本导入此文件时,我不喜欢调用主函数.
您可以使用以下检查:
如果pcall(debug.getlocal,4,1)然后打印(包装中")别的打印(在主脚本中")结尾
它检查第4层的第1个变量中是否有任何东西,如果是主模块,则为当前模块的调用者(如果需要),否则为空.
请注意,它不会区分 require
, dofile
, loadfile
或其他类似调用.您可能需要检查Lua邮件列表,其中讨论了检查这些呼叫以及其他方法.
I am writing a script testmodule.lua
and want to check that if this file is imported/required from another script or directly started by lua testmodule.lua
.
If it is directly started by command line I can do some test or run a main function, otherwise just export some function and do nothing.
Python has a __name__
statement:
if __name__ == '__main__':
main_entry()
Is there something similar in lua ??
It is useful to write a shell util in a single file, which can be run directly and imported by other lua scripts. But when some script import this file, I don't like main function to be called.
You can use the following check:
if pcall(debug.getlocal, 4, 1) then
print("in package")
else
print("in main script")
end
It checks if there is anything in the 1st variable at the 4th level, which would be the caller of the current module (if required) or nothing in the case of the main script.
Note that it doesn't distinguish between require
, dofile
, loadfile
or other similar calls. You may want to check this recent thread on the Lua mail list that discusses checking for these calls and some alternative ways as well.
这篇关于如何确定我的代码是否在lua模块中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!