lua

其实我一直都不喜欢 lua,感觉很多设计都是一坨屎,参见 lua 有多难用。但是现在是工作,不得不学了。

安装

配置:

其他:

基础

数据类型

string, function, boolean, number, nil, table

fs 与文件操作

文件 io:

lua
infile = io.open("input.txt", "r")
for line in infile:lines() do
   print(line)
end
infile:close()
local outfile, err = io.open("output.txt", "w") -- 可以加错误处理
if not outfile then
  outfile:write("\n")
end
outfile:close()

fs:使用 luafilesystem 库。

高级

gc

lua 5.4 之前使用的是增量 gc,使用较为细化的标记-清除过程。5.4 添加了分代特性,减少了老年代的扫描频次。

释放数据的标准做法是将其设为 nil,以便在下一次 gc 将其清理。

lua 可以通过下面的方式设置弱引用表,弱引用的部分不持有所有权:

lua
-- __mode = "k", "v" 或 "kv",代表哪部份是弱引用
local weakTable = setmetatable({}, {__mode = "k"})

根据这些 gc 机制,可以针对性注意,提升性能:

ffi

lua 的 ffi 开销比想象的要小。lua 不同类型的开销如下:

typing

lua 的一大缺点是没有 type system。类似 js 的 typed 加强版 ts,lua 也有 typed 加强版,不过比较杂,从早期已经久不维护的 typedlua 和一些 fork 到新的 teal,再到重新实现的 luau 都有。这些 typed 版本都受 ts 启发,语法比较相似。

external

  1. 理解 Lua 的闭包机制