TCAX 字幕特效制作工具官方论坛 | ASS | TCAS | Python | Aegisub | Lua

标题: 浅谈两种常见的lua表代码结构写法的优缺点 [打印本页]

作者: Seekladoom    时间: 2022-8-19 02:57:35     标题: 浅谈两种常见的lua表代码结构写法的优缺点

本帖最后由 Seekladoom 于 2022-8-19 03:01 编辑

第1种写法(实际案例:Yutils.lua)
  1. local test

  2. test = {
  3.         math = {
  4.                 distance = function(x, y, z)
  5.                         if type(x) ~= "number" or type(y) ~= "number" or z ~= nil and type(z) ~= "number" then
  6.                                 error("one vector (2 or 3 numbers) expected", 2)
  7.                         end
  8.                         return z and math.sqrt(x*x + y*y + z*z) or math.sqrt(x*x + y*y)
  9.                 end
  10.         },
  11. }

  12. return test
复制代码
优点:开发者进行长期开发维护时,以上述写法编写出来的lua代码在各种IDE中(VSCode、Sublime、Notepad++等)进行折叠代码操作时,熟悉快捷键的人可以迅速折叠当前不需要分析的代码,仅展开当前需要的部分进行分析,分析完之后在界面中上下翻动时,所需要的时间也更短。

如下图给出了在VSCode中折叠的例子:
F1.png


缺点:不知道折叠代码这个操作的人很难理解为什么要像上面这样写,代码长了的情况下就不好定当前的代码内容隶属于哪个上级表了。鄙人也是因为这点,给各个子表打了几百行各部分码对应的的注释。(然而知道折叠之后才发现这么做其实没必要)
F1-2.png


第2种写法(实际案例:Effector-utils-lib-3.5.lua)
  1. local test = {math = {}}

  2. function test.math.distance(x, y, z)
  3.         if type(x) ~= "number" or type(y) ~= "number" or z ~= nil and type(z) ~= "number" then
  4.                 error("one vector (2 or 3 numbers) expected", 2)
  5.         end
  6.         return z and math.sqrt(x*x + y*y + z*z) or math.sqrt(x*x + y*y)
  7. end

  8. return test
复制代码
优点:对初学者而言,可以尽可能控制表代码深度,有助于快速上手。
F2.png

缺点:如果进行长期开发,写出那种上万行的脚本以后,在脚本内要进行上下文本码分析,特别是叠代码的时候,就比较折磨了。这种写法做不到第1种写法那样高效折叠成千上万行代码。
F2-2.png


图片附件: F2-2.png (2022-8-19 02:56:24, 257.18 KB) / 下载次数 317
http://tcax.org/forum.php?mod=attachment&aid=MzAyNnxhOGQ1MDBlN3wxNzE0NjYyNzc0fDB8MA%3D%3D



图片附件: F2.png (2022-8-19 02:56:01, 109.86 KB) / 下载次数 355
http://tcax.org/forum.php?mod=attachment&aid=MzAyNXxjNjFhYmFiNnwxNzE0NjYyNzc0fDB8MA%3D%3D



图片附件: F1-2.png (2022-8-19 02:55:17, 109.69 KB) / 下载次数 320
http://tcax.org/forum.php?mod=attachment&aid=MzAyNHw0MGUwOGRhNXwxNzE0NjYyNzc0fDB8MA%3D%3D



图片附件: F1.png (2022-8-19 02:54:00, 166.6 KB) / 下载次数 356
http://tcax.org/forum.php?mod=attachment&aid=MzAyM3xmY2JhYjBlZXwxNzE0NjYyNzc0fDB8MA%3D%3D






欢迎光临 TCAX 字幕特效制作工具官方论坛 | ASS | TCAS | Python | Aegisub | Lua (http://tcax.org/) Powered by Discuz! X2