前面提到的Lua将全局变量都保存在一个 _G 表中,其实这个表就称为“环境(environment)”。
已经知道了,Lua 中不加 local 修饰的变量都是全局变量,并保存在 _G 中。
Lua 允许每个函数拥有一个 自己的环境来查找全局变量。
介绍一下关于环境的几个函数。
1. setfenv ( f, table )
Sets the environment to be used by the given function.
f
can be a Lua function or a number that specifies the function at that stack level:
Level 1 is the function calling setfenv
. setfenv
returns the given function.
As a special case, when f
is 0 setfenv
changes the environment of the running thread.
In this case, setfenv
returns no values.
setfenv: set function enviroment, 该函数设置函数环境。第一个参数 f 是一个函数,第二个参数
表示新的环境 table。f 还可以为数字,数字1表示当前函数,数字2表示调用当前函数的函数
2. getfenv ( [ f ] )
Returns the current environment in use by the function.
f
can be a Lua function or a number that specifies the function at that stack level:
Level 1 is the function calling getfenv
.
If the given function is not a Lua function, or if f
is 0, getfenv
returns the global environment.
The default for f
is 1.
返回函数当前使用的环境,参数表示指定的函数,是可选的,默认是1 表示调用 getfenv 的函数。