Lua优化—写得一手好代码
- 作者:admin
- /
- 时间:2021年03月08日
- /
- 浏览:2691 次
- /
- 分类:厚积薄发
在上期《Lua优化——认识局部变量中的常见陷阱》中,我们以UWA本地资源检测内相关的规则为依托,针对局部变量为大家介绍了在Lua中多种需要关注的使用场景,也结合简单的代码示例进行了直观说明。
本期,我们针对大家在写代码时的书写习惯,来分析Lua使用时可能发生的各种“笔误”情况,这些容易被忽视的问题,往往会带来一些无法预知的Bug。我们依然会以简单的例子来帮助大家读懂这些规则,力图以浅显易懂的表达,让职场新手或优化萌新能够深入理解。
1、控制流和数据流的问题
1.1 无法访问的代码

在如下代码中:
for i = 1, 100 do
if cond(i) then
f()
end
break
print("Unreachable code")
end
break的位置导致语句print("Unreachable code")不会执行。
1.2 循环最多可以执行一次

在如下代码中:
for i = 1, 100 do
if cond(i)
then f()
end
break
end
break的位置导致循环只能执行一次。
1.3 没有被使用的标签

在代码中书写了某个Label:
::LabelName::
但从未使用goto(LabelName)语句到达该位置。
1.4 赋值语句左侧变量少

例如:
local a=1,2
1.5 赋值语句左侧变量多

例如:
local a,b=1
1.6 do…end语句之间为空

在代码中书写了一段空的do..end分支:
do
end
1.7 空的if分支

在代码中书写了一段空的if分支:
if True then
else
end
1.8 空语句

Lua5.2+的版本中,分号被认为是语句。多个分号完全没有用,会Warning。例如:
;;;;;
1.9 函数的圈复杂度过高

圈复杂度( Cyclomatic complexity )也称为条件复杂度,是一种代码复杂度的衡量标准。
在软件测试的概念里,圈复杂度用来衡量一个模块判定结构的复杂程度,数量上表现为线性无关的路径条数,即合理的预防错误所需测试的最少路径条数。圈复杂度大说明程序代码可能质量低且难于测试和维护,根据经验,程序的可能错误和高的圈复杂度有着很大关系。
1.10 需要设置步长为负数

倒序遍历一个表的时候需要指定步长。例如以下这种错误的表达方式:
for i = #t, 1 do
print(t[i])
end
改正后结果应为:
for i = #t, 1, -1 do
print(t[i])
end
2、格式的问题
2.1 该行仅由空格组成

2.2 该行包含尾随空格

2.3 字符串中包含尾随空格

local string =[[xxxx #此处有空格
xxxxxxxxxxxxxxxx]]
2.4 注释中包含尾随空格

2.5 缩进不一致

一般是因为Tab之后有空格。但有些编译器会自动调整,例如“VS Code”。
Lua解析语法时是采用空格等分割来解析的,某些情况下,若不小心加空格会导致非预期的结果。上述五条规则都是在检查是否有不合理的空格存在。
2.6 该行过长

该条规则是为了代码的美观,在编写代码时注重代码书写上的简洁性,这样在后期修改和维护时能更方便查看。
希望以上这些简单的示例能在实际的开发过程中为大家带来帮助,从而最大程度上避开这些在使用Lua时会遇到的“笔误”问题。同时,也欢迎大家来使用UWA推出的本地资源检测服务,可帮助大家尽早对项目建立科学的检测规范。

万行代码屹立不倒,全靠基础掌握得好!
《场景检测:面片、光影和物理属性》
《场景检测:Audio Listener、RigidBody和Prefab连接》
《场景检测:雾效、Canvas和碰撞体》
《特效优化2:效果与性能的博弈》
《特效优化:发现绚丽背后的质朴》
《Prefab优化:预制体中的各种细节选择》
性能黑榜相关阅读
《那些年给性能埋过的坑,你跳了吗?》
《那些年给性能埋过的坑,你跳了吗?(第二弹)》
《掌握了这些规则,你已经战胜了80%的对手!》