Skip to content

Instantly share code, notes, and snippets.

@brynne8
Created October 20, 2021 13:36
Show Gist options
  • Save brynne8/aa698c2e98f477f23dd9492b5fe19627 to your computer and use it in GitHub Desktop.
Save brynne8/aa698c2e98f477f23dd9492b5fe19627 to your computer and use it in GitHub Desktop.
加快Lua的小技巧

本文来自https://luapower.com/lua-tricks

这是一个Lua习语和技巧的集合,对于随意阅读代码的人来说,可能不会立即看到。

逻辑
not a == not b 两者都满足或都不满足
数字
math.min(math.max(x, min), max) 把x限制在[min, max]区间内
x ~= x 一个数是NaN
1/0 inf
-1/0 -inf
math.huge == math.huge-1 检查inf是否可用而不需要除以0
x % 1 小数部分(总是正数)
x % 1 == 0 数字是整数;math.floor(x) == x
x - x % 1 整数部分,不过最好用 math.floor(x)
x - x % 0.01 x保留两位小数
x - x % n x 小的,最接近x的, n的整数倍
math.modf(x) 整数部分和小数部分
math.floor(x+.5) 四舍五入
(x >= 0 and 1 or -1) 正负号
y0 + (x-x0) * ((y1-y0) / (x1 - x0)) 线性内插
math.fmod(angle, 2*math.pi) 对一个角度进行归一化
tables
next(t) == nil table为空
strings
s:match'^something' 以…起始
s:match'something$' 以…结束
s:match'["\'](.-)%1' 匹配成对的单引号或双引号
i/o
f:read(4096, '*l') 快速读取行
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment