Lua Programming Language

生成一个随机数

function GetTrueRandom(min,max)
    --得到时间字符串
    local strTime=tostring(os.time())
    --得到一个反转字符串
    local strRev=string.reverse(strTime)
    --得到前6位
    local strRandomTime=string.sub(strRev, 1, 6)
 
    --设置时间种子
    math.randomseed(strRandomTime)
    --输出随机数
    --print("#随机数=",math.random(min, max))
    return math.random(min, max)
end

保存文件

  • r“: read mode (the default);
  • w“: write mode;
  • a“: append mode;
  • r+“: update mode, all previous data is preserved;
  • w+“: update mode, all previous data is erased;
  • a+“: append update mode, previous data is preserved, writing is only allowed at the end of file.
local fp, err = io.open(filename, mode)
if err ~= nil {
    -- check error status
}
fp:write(data)
fp:close()

nginx打印日志:

nginx log 日志级别

   ngx.STDERR
   ngx.EMERG
   ngx.ALERT
   ngx.CRIT
   ngx.ERR
   ngx.WARN
   ngx.NOTICE
   ngx.INFO
   ngx.DEBUG
ngx.log(ngx.ERR, message)

ngx log的坑

出于性能考虑,ngx log 最多能打印的日志长度为2K字节,多余的会被截断。

解压缩gzip压缩的数据

local zip = require("zlib")

local stream = zlib.inflate()
local decompress_data = stream(compressed_data)