lua脚本的一些语法
文档地址 https://www.runoob.com/lua/lua-variables.html
lua的一些语法
-
local就是局部变量
-
key [key ...]: 从 EVAL 的第三个参数开始算起,表示在脚本中所用到的那些 Redis 键(key),这些键名参数可以在 Lua 中通过全局变量 KEYS 数组,用 1 为基址的形式访问( KEYS[1] , KEYS[2] ,以此类推)。
-
arg [arg ...]: 附加参数,在 Lua 中通过全局变量 ARGV 数组访问,访问的形式和 KEYS 变量类似( ARGV[1] 、 ARGV[2] ,诸如此类)。
-
.. 是字符串连接符
-
num = tonumber(str, base)
参数 类型 必填 说明 str string 是 需要转换的字符串 base string 否 原字符进制类型,不写默认为 10 -
redis.call(command [,arg...])
redis.call() 函数调用给定的 Redis 命令并返回其回复。其输入是命令和参数,调用后,它在 Redis 中执行命令并返回回复。
文档地址 https://redis.ac.cn/docs/interact/programmability/lua-api/
代码示例
-- 1.参数列表
-- 1.1优惠卷id
local voucherId = ARGV[1]
-- 1.2用户id
local userId = ARGV[2]
-- 2.数据key
-- 2.1库存key
local stockKey = 'seckill:stock:' .. voucherId
-- 2.2订单key
local orderKey = 'seckill:order:' .. voucherId
-- 3.脚本业务
-- 3.1判断库存是否充足
if(tonumber(redis.call('get',stockKey)) <= 0)then
-- 3.2 库存不足 返回1
return 1
end
--3.2判断用户是否下单
if(redis.call('sismember',orderKey,userId) == 1) then
-- 3.3存在,说明是重复下单
return 2
end
-- 3.4扣库存
redis.call('incrby',stockKey,-1)
-- 3.5下单并保存用户
redis.call('sadd',orderKey,userId)
return 0