当前位置:网站首页>do end用法的妙处
do end用法的妙处
2022-07-29 07:01:00 【森明帮大于黑虎帮】
为什么要使用do end,它到底能够解决什么问题呢;首先,语句块不是用花括号 { } , 而是 do 语句块 end 表示语句块的开始和结束。而 花括号 {} 表示的为一个 表结构 。
do-end blocks它解决的是变量作用域的问题,首先必须要明白local变量和全局变量拥有完全不同的词法作用域;我们应该尽量声明local变量,尽量减少一个变量的作用域范围,使其仅存在于自己需要的变量块内,而不要污染更大范围内的公共环境;
首先参考一下两个例子:
do
local x1=1
local x2=2
local sum=x1+x2
end
print(x1,x2) --nil nil
没有do end:
local x1=1
local x2=2
local sum=x1+x2
print(x1,x2) --1 2
在 Lua 中,使用 do-end 将一条或多条语句包起来作为一个语句块儿(block),形成一个作用域,在这个作用域中定义的局部变量只在当前作用域有效,出了作用域之后就会被垃圾回收器自动回收!
do
local l_var = 1 -- 局部变量
g_var = 2 -- 全局变量
print(l_var, g_var) -- 1 2
end
print(l_var, g_var) -- nil 2
在作用域中定义的全局变量不受作用域的影响!
边栏推荐
- Excel file reading and writing (creation and parsing)
- Zabbix 其他基础监控项
- Win11 system error: code execution cannot continue because ierutil.dll cannot be found. Reinstalling the program may fix this problem
- 5-integrate swagger2
- Gin Middleware
- Vagrant box cluster processing
- 使用VsCode配置MySQL实现连接、查询、等功能
- 20-40k | mecarmand 3D vision algorithm / software / Product Manager Recruitment
- 个人博客系统(附源码)
- log4j Layout简介说明
猜你喜欢

微服务远程调用

0 9 布隆过滤器(Bloom Filter)

JS day 4 process control (if statement and switch statement)

一篇长文---深入理解synchronized

【OpenGL】着色器(Shader)的使用

MySQL如何把行转换为列?

用户列表 圆形头像并跟随小板块

QT basic day 2 (2) QT basic components: button class, layout class, output class, input class, container and other individual examples

WPF interface layout must know basis

WPF nested layout case
随机推荐
利用C语言巧妙实现棋类游戏——三子棋
QT专题:基础部件(按钮类,布局类,输出类,输入类,容器类)
Does Flink support sqlserver databases? Get the changes of SQLSERVER database
Explanation of suffix automata (SAM) + Luogu p3804 [template] suffix automata (SAM)
Remote invocation of microservices
MySQL 使用客户端以及SELECT 方式查看 BLOB 类型字段内容总结
Operator3-设计一个operator
Win11 system error: code execution cannot continue because ierutil.dll cannot be found. Reinstalling the program may fix this problem
js第四天流程控制(if语句和switch语句)
3-全局异常处理
MySQL 有这一篇就够(呕心狂敲37k字,只为博君一点赞!!!)
OCR光学字符识别方法汇总
JS 鸡生蛋与蛋生鸡问题,Object与Function究竟谁出现的更早?Function算不算Function的实例?
Homebrew brew update doesn't respond for a long time (or stuck in updating homebrew...)
Why does ETL often become ELT or even let?
Use vscode to configure Mysql to realize connection, query, and other functions
以太网接口介绍
Nodejs installation tutorial
Excel file reading and writing (creation and parsing)
Ansible中的变量及加密