lua脚本

Lua是一个小巧的脚本语言由标准C编写而成, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能.Lua和redis搭配使用也可以应对高并发等业务.

1.Lua语法
Lua是一个对大小写敏感的语言.
Lua中有八种基本类型:nil,boolean,number,string,function,userdata,thread,table. Nil类型只有一种值nil,它的主要用途用于标表识和别的任何值的差异.
–和–[[]]–是注释

1、1控制语句
if else语句
if a==1 and b==1 then
elseif c>1 or d~=1 then
else
end

while循环
a=0
while a<= 100 do end for循环 for a = 0,100,2 do end until循环 a = 2 repeat print(a) until a>100

1、2函数
aaa = function(a) return a^2 end
function aaa(a)
if a < 2 then return 1 end return aaa(n - 2) + aaa(n - 1) end

1、3Table
aaa = {name=”hello”,age=11,handsome=True}
aaa.name = “hello”
aaa.age = 11
aaa.handsome = True

1、4全局变量
_G.aaa
_G[“aaa”]
for k, v in pairs(t) do
print(k, v)
end

1、5模块
直接使用require(“model_name”)来载入别的lua文件

官网中文文档http://manual.luaer.cn/

2.redis应用Lua
文档地址https://www.github.com/phpredis/phpredis
由于redis eval和lua是队列运行,能够承受高并发问题,而且请求也可以合并一个,减少服务器之间的通信。
列如:
$unique_redis_rand = <<<_ --获得已经抽了多少次 local now_num = tonumber(redis.call("hget","lotterycount_$event_id","$rand_con_id")) --获得一天抽奖次数 local now_num_day = tonumber(redis.call("hget","lotterycount_$event_id","$rand_con_id_day")) --获得个人抽奖次数 local now_num_user = tonumber(redis.call("hget","lotterycount_$event_id","$userid")) --判断是否开始 if not now_num then now_num = 0 end --一天限额如果没有默认0 if not now_num_day then now_num_day = 0 end --判断抽奖是否超过总限额 if now_num >= $rand_con_total then
return 0
–判断抽奖是否超过日限额
elseif now_num >= $now_total then
return 0
–判断抽奖是否超过规定日限额
elseif now_num_day >= $now_total_day then
return 0
–判断用户是否还有资格
elseif now_num_user <= 0 return 0 else --减掉用户次数 --这块也可以加上在redis队列取出礼包放入用户属性中,或者其他操作 return {1,redis.call("hincrby","lotterycount_$event_id","$userid","-1")} end _; $return = $redis->eval($unique_redis_rand);

//防IP刷Lua脚本形式
$date_mobile = “13200000000”;
$date_json = “hello word”;
$user_ip = ‘127.0.0.1’;
$date_cname = ‘test’;

$key_ip = ‘gus_ban_’.$user_ip;
$key_mobile = ‘gus_mobile_’.$date_cname;
$key_con = ‘gus_link’;
//lua start
$lua_cont = <<<_ local ip_num = redis.call("incr",KEYS[1]) if ip_num >= 100 then
return 2
end
if ip_num == 1 then
redis.call(“expire”,KEYS[1],”60″)
end
local mobile_not = redis.call(“sismember”,KEYS[2],ARGV[1])
if mobile_not == 0 then
redis.call(“sadd”,KEYS[2],ARGV[1])
redis.call(“lpush”,KEYS[3],ARGV[2])
return 1
else
return 3
end
_
;
$return = Redis::eval($lua_cont,3,$key_ip,$key_mobile,$key_con,$date_mobile,$date_json);
//lua end

猜你喜欢

转载自yuhuiblog6338999322098842.iteye.com/blog/2422316