1.基本语法
1.1变量
lua的变量有:无效值nil,布尔值boolean,数字number、字符串string、函数function、自定义类型userdata、线程thread、表table(key-value结构)
1.2循环
数值循环
for i=起始值, 结束值 ,间隔值 do
---options
end
间隔值为1时可以省略。像python里面的range()函数
迭代循环
for k,v in pairs(tb) do
print(k,v)
end
while循环
while(condition)
do
---options
ee
repeat -until
repeat
-- statements
until( condition )
1.3条件语句
if(con1) then
-----option--
elseif(con2) then
----option
elseif(con3) then
---option
end
1.4函数的定义
function a(num)
print("hello"..num) //字符串拼接用的 .. 而不是+,1+'1'=2.0
end
a=function()
print('a')
end
函数定义默认都全局的,即使是嵌套在其它函数里面,如果想定义局部的函数,需要使用local关键字修饰。
2.lua脚本在redis中的使用
查看redis当前有哪些key没有设置过期时间,内存满的时候可以进行排查
-- 获取所有key的模式(默认为*)
local pattern = ARGV[1] or '*'
local result = {keys = {}, stats = {total = 0, neverexpire = 0}}
local start_time = redis.call('TIME')[1]
-- 使用SCAN迭代
local cursor = '0'
repeat
local reply = redis.call('SCAN', cursor, 'MATCH', pattern)
cursor = reply[1]
local keys = reply[2]
-- 检查每个key
for _, key in ipairs(keys) do
result.stats.total = result.stats.total + 1
local ttl = redis.call('TTL', key)
if ttl == -1 then
table.insert(result.keys, key)
result.stats.neverexpire = result.stats.neverexpire + 1
end
end
until cursor == '0'
-- 计算执行时间
local end_time = redis.call('TIME')[1]
result.stats.duration = end_time - start_time
-- 返回结果
if #result.keys == 0 then
return "没有永不过期的key (共扫描: "..result.stats.total.." 个key, 耗时: "..result.stats.duration.."秒)"
else
result.msg = "找到 "..result.stats.neverexpire.." 个永不过期的key (共扫描: "..result.stats.total.." 个key, 耗时: "..result.stats.duration.."秒)"
return result
end
--------------------------------
以上内容由AI生成,仅供参考和借鉴
lua脚本实现分布式锁
-- 获取锁
-- KEYS[1]: 锁的key
-- ARGV[1]: 锁的值(通常是客户端唯一标识)
-- ARGV[2]: 过期时间(秒)
local key = KEYS[1]
local value = ARGV[1]
local ttl = tonumber(ARGV[2])
-- 尝试设置锁(NX表示key不存在时才设置,EX表示设置过期时间)
local lockSet = redis.call('SET', key, value, 'NX', 'EX', ttl)
if lockSet then
return true
else
-- 检查锁是否是自己持有的(防止误删其他客户端的锁)
local currentValue = redis.call('GET', key)
if currentValue == value then
-- 延长锁的过期时间
redis.call('EXPIRE', key, ttl)
return true
else
return false
end
end