如何检查脚本是否通过dofile()包含或直接在Lua中运行? [英] How to check if a script is included via dofile() or run directly in Lua?

查看:279
本文介绍了如何检查脚本是否通过dofile()包含或直接在Lua中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
“ main”在Lua中起作用?

Possible Duplicate:
“main” function in Lua?

在Python中,您可以很容易地检查是否直接调用了脚本(如果需要,通常会进行测试,然后调用某些函数):

In Python, you can check if a script is being called direcly (and call some functions if it is, usually for testing) pretty easily:

if __name__ == "__main__":
    main()

是否可以在Lua中执行相同的操作,以检测它是直接运行(lua foo.lua)还是包含在另一个脚本(dofile('foo.lua'))中.

Is there a way to do the same in Lua, to detect if it is run directly (lua foo.lua) or included in another script (dofile('foo.lua')).

总是有一种琐碎的(而且很丑陋的)方式,即在dofile('foo.lua')之前的主脚本文件中定义一些虚拟全局变量,并检查foo.lua是否已定义,但是如果有的话会很棒更好的方法.

There is always the trivial (and ugly) way of defining some dummy global variable in the main script file before dofile('foo.lua'), and checking in foo.lua if it is defined or not, but it would be great if there was a better way to do this.

推荐答案

在顶层,您可以检查debug.getinfo(2)是否为零

At the top level you can check if debug.getinfo(2) is nil

来自 http://www.lua.org/manual /5.1/manual.html#pdf-debug.getinfo

您可以给数字作为function的值,这意味着该函数在给定线程的调用堆栈的level函数上运行:level 0是当前函数(getinfo本身); 1级是调用getinfo的函数;等等.如果function的数量大于活动函数的数量,则getinfo返回nil.

you can give a number as the value of function, which means the function running at level function of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo; and so on. If function is a number larger than the number of active functions, then getinfo returns nil.

这篇关于如何检查脚本是否通过dofile()包含或直接在Lua中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆