---
title: "Lua基础整理"
author: "username2"
date: "2019-07-30T20:24:29Z"
tags: []
categories: ["编程语言"]
slug: "lua"
draft: false
lastmod: "2019-07-30T20:24:29Z"
id: 2443083
url: "https://username2.iteye.com/blog/2443083"
---

https://github.com/openresty/lua-nginx-module#status

 

 

and逻辑与操作符。 “短路求值” 若 A 为 false，则返回 A，否则返回 B。(A and B) 为 false。

or逻辑或操作符。“短路求值”  若 A 为 true，则返回 A，否则返回 B。(A or B) 为 true。

lua中除了false和nil之外，其他所以数据，包括0、空字符串等都是true。

类型：

print(type("Hello world"))      --&gt; string

print(type(10.4\*3))             --&gt; number

print(type(print))              --&gt; function

print(type(type))               --&gt; function

print(type(true))               --&gt; boolean

print(type(nil))                --&gt; nil

print(type(type(X)))            --&gt; string

 

nil删除功能：对于全局变量和 table，nil 还有一个"删除"作用，给全局变量或者 table 表里的变量赋一个 nil 值，等同于把它们删掉

nil 作比较时应该加上双引号 "：  type(X)=="nil" --- true

Lua 把 false 和 nil 看作是"假"，其他的都为"真":

字符串和数字：一个数字字符串上进行算术操作时，Lua 会尝试将这个数字字符串转成一个数字

字符串连接：print("a" .. 'b')  tonumber(字符串)  -- tostring(bVar)

字符串长度：使用 # 来计算字符串的长度，放在字符串前面

table类型：

1、不同于其他语言的数组把 0 作为数组的初始索引，在 Lua 里表的默认初始索引一般以 1 开始

2、"关联数组"（associative arrays），数组的索引可以是数字或者是字符串。

3、table 不会固定长度大小，有新数据添加时 table 长度会自动增长，没初始的 table 都是 nil

函数是被看作是"第一类值（First-Class Value）"，函数可以存在变量里:

table类型是否为nil变量

function isTableEmpty(t)

    if t == nil or \_G.next(t) == nil then

        return true

    else

        return false

    end

end

 

全局变量和局部变量：a = 5  -- 全局变量 local b = 5         -- 局部变量

Lua 可以对多个变量同时赋值，变量列表和值列表的各个元素用逗号分开，赋值语句右边的值会依次赋给左边的变量。

赋值规则：a. 变量个数 &gt; 值的个数             按变量个数补足nil

  b. 变量个数 &lt; 值的个数             多余的值会被忽略

对 table 的索引使用方括号 \[]。Lua 也提供了 . 操作

 

循环：

while( true )

do

   print("循环将永远执行下去")

end

 

if(0)

then

    print("0 为 true")

end

 

 

 

 

for k, v in pairs(tab1) do

    print(k .. " - " .. v)

end

函数：Lua函数可以返回多个结果值，比如string.find，其返回匹配串"开始和结束的下标"（如果不存在匹配串返回nil）。

Lua 函数可以接受可变数目的参数，和 C 语言类似，在函数参数列表中使用三点 ... 表示函数有可变的参数

我们也可以通过 select("#",...) 来获取可变参数的数量:

有时候我们可能需要几个固定参数加上可变参数，固定参数必须放在变长参数之前

 

通常在遍历变长参数的时候只需要使用 {…}，然而变长参数可能会包含一些 nil，那么就可以用 select 函数来访问变长参数了：select('#', …) 或者 select(n, …)

select('#', …) 返回可变参数的长度

select(n, …) 用于访问 n 到 select('#',…) 的参数

 

table数结构：

table 是 Lua 的一种数据结构用来帮助我们创建不同的数据类型，如：数组、字典等。

Lua table 使用关联型数组，你可以用任意类型的值来作数组的索引，但这个值不能是 nil。

Lua table 是不固定大小的，你可以根据自己需要进行扩容。

Lua也是通过table来解决模块（module）、包（package）和对象（Object）的。 例如string.format表示使用"format"来索引table string

 

 

 

 

 

 

 

 

https://github.com/openresty/lua-nginx-module#introduction

 

 

content\_by\_lua 是内容处理器，接受请求并输出响应，适用于location、location if。 

access\_by\_lua 在请求访问阶段处理，用于访问控制，适用于http、server、location、location if。

rewrite\_by\_lua

set\_by\_lua

set\_by\_lua\_file执行Nginx外部的lua脚本，可以避免在配置文件中使用大量的转义

 

 

location / {

rewrite\_by\_lua '

local res = ngx.location.capture("/check-spam")

if res.body == "spam" then

ngx.redirect("/terms-of-use.html")

end

'; fastcgi\_pass ...;

}

 

location /echo {

default\_type text/plain;

echo hello lua;

}

 

location /lua {

default\_type text/plain;

content\_by\_lua 'ngx.say("hello world")';

}

 

 

ip禁止功能

location @client{

proxy\_pass  http://www.baidu.com;

}

location ~  /test {

default\_type  text/html;

content\_by\_lua 'ngx.say("this is  ruifengyun.com!")';

access\_by\_lua '

if ngx.var.remote\_addr == "10.2.20.110" then

ngx.exit(ngx.HTTP\_FORBIDDEN)

end

if ngx.var.remote\_addr == "10.2.20.112" then

ngx.exec("@client")

end

';

}

 

重定向转发-获取重定向的参数

location /foo {

 content\_by\_lua\_block {

     ngx.exec("/bar", "a=goodbye");

 }

}

 

 

location /bar {

 default\_type text/plain;

 content\_by\_lua\_block {

     local args = ngx.req.get\_uri\_args()

     for key, val in pairs(args) do

if key == "a" then

     ngx.say(val)

end

     end

 }

}

 

nginx定义的变量 lua中可以获取

 

 location /foo {

     set $my\_var ''; # this line is required to create $my\_var at config time ngx.arg\[1]可以获取定义的参数

     content\_by\_lua\_block {

         ngx.var.my\_var = 123;

         ...

     }

 }

删除变量 ngx.var.args = nil如：ngx.var.name = nil 删除nginx中name的变量 

 

 

ngx.ctx-一个生命周期中共享变量

 location /test {

     rewrite\_by\_lua\_block {

         ngx.ctx.foo = 76

     }

     access\_by\_lua\_block {

         ngx.ctx.foo = ngx.ctx.foo + 3

     }

     content\_by\_lua\_block {

         ngx.say(ngx.ctx.foo)

     }

 }

 

 

  ngx.HTTP\_GET

  ngx.HTTP\_HEAD

  ngx.HTTP\_PUT

  ngx.HTTP\_POST

  ngx.HTTP\_DELETE

  ngx.HTTP\_OPTIONS   (added in the v0.5.0rc24 release)

  ngx.HTTP\_MKCOL     (added in the v0.8.2 release)

  ngx.HTTP\_COPY      (added in the v0.8.2 release)

  ngx.HTTP\_MOVE      (added in the v0.8.2 release)

  ngx.HTTP\_PROPFIND  (added in the v0.8.2 release)

  ngx.HTTP\_PROPPATCH (added in the v0.8.2 release)

  ngx.HTTP\_LOCK      (added in the v0.8.2 release)

  ngx.HTTP\_UNLOCK    (added in the v0.8.2 release)

  ngx.HTTP\_PATCH     (added in the v0.8.2 release)

  ngx.HTTP\_TRACE     (added in the v0.8.2 release)

 

 

 ngx.STDERR

   ngx.EMERG

   ngx.ALERT

   ngx.CRIT

   ngx.ERR

   ngx.WARN

   ngx.NOTICE

   ngx.INFO

   ngx.DEBUG

 

 

ngx.redirect("http://jd.com", 302)  

 

   value = ngx.HTTP\_OK (200)

   value = ngx.HTTP\_CREATED (201)

   value = ngx.HTTP\_ACCEPTED (202) (first added in the v0.9.20 release)

 

ngx.req.read\_body

 

打印日志：

ngx.log(log\_level, ...)

 ngx.log(ngx.NOTICE, ...)

  ngx.header.content\_type = 'text/plain';

 ngx.header\["X-My-Header"] = 'blah blah';

 

 local request\_time = ngx.now() - ngx.req.start\_time()

ngx.req.get\_method

ngx.req.set\_method

 

 重定向：

 ngx.req.set\_uri

 ngx.req.set\_uri("/foo", true)

ngx.req.get\_uri\_args

ngx.req.set\_uri\_args

local args, err = ngx.req.get\_post\_args()

ngx.req.get\_headers

ngx.req.set\_header

ngx.req.clear\_header

ngx.req.read\_body

ngx.req.get\_body\_file

 

ngx.req.set\_body\_data

 

ngx.redirect

ngx.print 没有回车 

ngx.say 有回车 

 

ngx.flush

ngx.exit(501) 返回状态吗，并直接退出 

ngx.sleep

ngx.today

ngx.time

ngx.now

ngx.update\_time

ngx.utctime

ngx.re.match

ngx.re.find

ngx.re.gmatch

ngx.re.sub

ngx.re.gsub

ngx.shared.DICT

local ok, err = ngx.timer.at(2, mylog ) 延时器，只会执行一次 

 

--写响应头  

ngx.header.a = "1"  

--多个响应头可以使用table  

ngx.header.b = {"2", "3"}  

--输出响应  

ngx.say("a", "b", "&lt;br/&gt;")  

ngx.print("c", "d", "&lt;br/&gt;")  

--200状态码退出  

return ngx.exit(200)  

 

必须调用exit给出状态码

ngx.say("api is offline!")

ngx.exit(200)

 

 

 

获取消息体，先打开获取消息体的开关：

ngx.req.read\_body()

local data = ngx.req.get\_body\_data()

 

加载table.new这个模块，作用为：为新创建的table类型分配空间：ok, new\_tab = pcall(require, "table.new")

 

resty.iputils 工具类使用：https://github.com/hamishforbes/lua-resty-iputils

 

https://www.kancloud.cn/allanyu/openresty-best-practices/82647

客户端的IP：ngx.var.binary\_remote\_addr