utils
字符串 / 编码 / 哈希 / 时间 / 剪贴板 / 持久化等域无关的通用工具。
编码
utils.base64_encode(text) → string
标准 RFC 4648 base64 编码,带 = 填充。输入按 byte 流处理(可含 \0 等任意字节)。
utils.base64_decode(text) → string
解码 base64。跳过 \n / \r / 空格;非法字符容错(不报错)。= 填充自动识别。
utils.array_to_string(bytes) → string
1-based byte table 转字符串(元素 0-255)。配 file.read 不适用——file.read 直接返 string;这俩主要给手写二进制协议用。
utils.string_to_array(text) → table<int>
字符串转 1-based byte table。
哈希
utils.murmur2(text) → int
MurmurHash2 32-bit (Austin Appleby 原版, seed=0)。返 uint32(LuaJIT 整数安全到 2^53)。
utils.fnv1a(text) → int
FNV-1a 32-bit。
时间
utils.unix_time() → int
当前 unix 时间戳(秒)。跟 time.now() 区别:time.now() 是 steady_clock 单调时间不是 wall clock;要日志戳/server 同步用 unix_time()。
utils.get_date() → table
当前本地日期时间,返回 {year, month, day, hour, minute, second, dst}。
剪贴板
剪贴板已迁出 utils.*,请使用 input.clipboard_get / input.clipboard_set。
脚本级 KV 持久化
db_save / db_load 用来存只属于本脚本的数据(区别于 config.* 全局配置)。落盘路径 conf/lua_db/<owner-hash>__<key>.json,owner 自动 = 当前 _SCRIPT_PATH,所以同名 key 在不同脚本互不干扰。
值走 json.encode/decode 序列化,所以接受 table / string / number / bool / nil(function/userdata 不行)。
utils.db_save(key, value) → bool
key:[a-zA-Z0-9_.-]+且 ≤64 字符;非法返false。- 成功返
true,失败 log error。
utils.db_load(key, default?) → value
- key 同上规则。
- 不存在/解析失败返
default(默认nil)。
示例
-- HTTP Basic Auth
local cred = utils.base64_encode("user:pass")
net.http:get("https://api.example.com/private", {
headers = { ["Authorization"] = "Basic " .. cred }
}, function(r) end)
-- 哈希配置 id 做去重
local id = utils.fnv1a(json.encode(cfg))
-- 日志带时戳
log.info(("[%d] %s"):format(utils.unix_time(), msg))
-- 每天打一次条
local d = utils.get_date()
local today = ("%04d-%02d-%02d"):format(d.year, d.month, d.day)
if utils.db_load("last_day") ~= today then
log.info("new day: " .. today)
utils.db_save("last_day", today)
end
-- 跨 session 保留 UI 状态
local saved = utils.db_load("ui_pos", { x = 100, y = 100 })
event.on("frame_update", function()
-- ... 拖动后:
utils.db_save("ui_pos", { x = win.x, y = win.y })
end)