当前位置:网站首页>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
在作用域中定义的全局变量不受作用域的影响!
边栏推荐
- Some learning and understanding of vintage analysis
- logback日志级别简介说明
- 对Vintage分析的一些学习理解
- 【OpenGL】着色器(Shader)的使用
- Interface test actual project 03: execute test cases
- Use vscode to configure Mysql to realize connection, query, and other functions
- Spingboot integrates the quartz framework to realize dynamic scheduled tasks (support real-time addition, deletion, modification and query tasks)
- logback简介及引入方法
- Problems encountered in vmware16 installing virtual machines
- 同步/异步、阻塞/非阻塞 与 IO
猜你喜欢

How does MySQL convert rows to columns?

作业7.28 文件IO与标准IO

MySQL advanced (Advanced) SQL statement (I)

女研究生做“思维导图”与男友吵架!网友:吵架届的“内卷之王”....
![[Charles' daily problems] when you open Charles, you can't use nails](/img/ef/037fc416175d4de769ac6484cb53df.png)
[Charles' daily problems] when you open Charles, you can't use nails

Vite3.0都发布了,你还能卷得动吗(新特性一览)

Round avatar of user list and follow small blocks

论文阅读 (62):Pointer Networks

以太网接口介绍

利用C语言巧妙实现棋类游戏——三子棋
随机推荐
Latest 10 billion quantitative private placement list
0 8 动态规划(Dynamic Programming)
Explanation of suffix automata (SAM) + Luogu p3804 [template] suffix automata (SAM)
thinkphp6 实现数据库备份
JS 鸡生蛋与蛋生鸡问题,Object与Function究竟谁出现的更早?Function算不算Function的实例?
Remote invocation of microservices
H3C_利用设置缺省静态路由优先级实现出口双线路的主备功能
JS day 4 process control (if statement and switch statement)
5-整合swagger2
My personal website doesn't allow access to wechat, so I did this
After 4 years of development and 13K, if you want to change to automated testing, can your salary still rise···
Spark Learning Notes (VII) -- spark core core programming - RDD serialization / dependency / persistence / partition / accumulator / broadcast variables
Homebrew brew update 长时间没反应(或卡在 Updating Homebrew...)
NPM install reports an error NPM err could not resolve dependency NPM err peer
Vmware16 create virtual machine: win11 cannot be installed
Section 7 - compilation of programs (preprocessing operations) + links
H3C_ Using setting default static routing priority to realize the active and standby function of export dual lines
Problems encountered in vmware16 installing virtual machines
Custom events
微服务远程调用