Lua语言学习之环境


前面提到的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 setfenvsetfenv 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 的函数。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值