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
enda=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'
repeatlocal reply = redis.call('SCAN', cursor, 'MATCH', pattern)cursor = reply[1]local keys = reply[2]-- 檢查每個keyfor _, key in ipairs(keys) doresult.stats.total = result.stats.total + 1local ttl = redis.call('TTL', key)if ttl == -1 thentable.insert(result.keys, key)result.stats.neverexpire = result.stats.neverexpire + 1endend
until cursor == '0'-- 計算執行時間
local end_time = redis.call('TIME')[1]
result.stats.duration = end_time - start_time-- 返回結果
if #result.keys == 0 thenreturn "沒有永不過期的key (共掃描: "..result.stats.total.." 個key, 耗時: "..result.stats.duration.."秒)"
elseresult.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 thenreturn true
else-- 檢查鎖是否是自己持有的(防止誤刪其他客戶端的鎖)local currentValue = redis.call('GET', key)if currentValue == value then-- 延長鎖的過期時間redis.call('EXPIRE', key, ttl)return trueelsereturn falseend
end