Skip to content

Commit e21b110

Browse files
committed
ops/network-service: Basic lua
1 parent ec14677 commit e21b110

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

docs/ops/network-service/nginx.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,6 +1083,68 @@ access_log /var/log/nginx/access.log combined if=$log_normal;
10831083

10841084
## Lua {#lua}
10851085

1086+
由 OpenResty 团队维护的 [ngx_http_lua_module](https://github.com/openresty/lua-nginx-module) 提供了非常强大的 Lua 支持,可以在 Nginx 处理请求的各个阶段运行 Lua 脚本,实现复杂的逻辑。此外,Nginx 官方维护的 [ngx_http_js_module](https://nginx.org/en/docs/http/ngx_http_js_module.html) ([njs](https://nginx.org/en/docs/njs/index.html)) 也提供了类似的使用 JavaScript 脚本的功能,但就目前而言,Lua 模块的生态更加丰富,功能也更强大。
1087+
1088+
### Lua 语言简介 {#lua-intro}
1089+
1090+
Lua 是一种轻量的脚本语言,可以轻松集成到其他应用程序中,并且在 LuaJIT 的支持下,可以达到非常好的性能,常被用于游戏开发,以及各种需要用户自定义运行逻辑的场景。
1091+
1092+
#### Lua 基础语法 {#lua-basic-syntax}
1093+
1094+
以下给出一个简单的 Lua 代码示例,展示基本的语法,可以在 Lua 解释器中运行。如果希望进一步学习 Lua,可以参考[官方文档](https://www.lua.org/manual/)以及 [Programming in Lua](https://www.lua.org/pil/contents.html) 一书。
1095+
1096+
```lua
1097+
-- 这是注释
1098+
1099+
local version = "1.0" -- 使用 local 定义局部变量
1100+
if version ~= "1.0" then -- ~= 表示不等于
1101+
print("Version is not 1.0")
1102+
else
1103+
print("Version is 1.0")
1104+
end
1105+
if something_not_defined == nil then -- nil 表示空值/未定义
1106+
print("A nil variable")
1107+
end
1108+
1109+
-- 字符串正则匹配与替换
1110+
local str = "Hello, Lua 123!"
1111+
local match = string.match(str, "%d+")
1112+
local match_2 = str:match("%d+") -- 冒号语法糖,等价于 str.match(str, pattern)
1113+
local new_str = str:gsub("%d+", "456"):lower() -- gsub 替换,lower 转小写
1114+
assert(match == match_2, "Matches should be equal")
1115+
print(match)
1116+
print(new_str)
1117+
1118+
-- Lua 中的表(table)可以用来表示数组、字典(键值对)等数据结构
1119+
local map = {
1120+
{"host", "host"},
1121+
{"server", "server_addr"},
1122+
{"ts", "msec"},
1123+
{"ip", "remote_addr"},
1124+
{"ua", "http_user_agent"}
1125+
} -- 定义一个表(数组)
1126+
local another_map = {
1127+
host = "www.example.com", -- 或者 ["host"] = "www.example.com"
1128+
server_addr = "www.example.com",
1129+
msec = 1234567890,
1130+
remote_addr = "127.0.0.1",
1131+
http_user_agent = "Mozilla/5.0"
1132+
} -- 定义一个表(字典)
1133+
local result = {}
1134+
1135+
-- 循环,使用 ipairs 遍历表,类似 Python 的 enumerate
1136+
for _, pair in ipairs(map) do
1137+
-- 使用 table.insert 向表中添加元素
1138+
-- 使用 .. 进行字符串连接
1139+
-- Lua 的下标从 1 开始,不是 0!
1140+
table.insert(result, pair[1] .. "=" .. another_map[pair[2]])
1141+
end
1142+
1143+
print(table.concat(result, "\n")) -- 使用 table.concat 将表元素连接成字符串
1144+
```
1145+
1146+
#### Lua 模块 {#lua-modules}
1147+
10861148
## 示例介绍 {#examples}
10871149

10881150
<!-- 以下给出一些实践中会使用的 Nginx 配置示例。

0 commit comments

Comments
 (0)