@@ -1141,10 +1141,83 @@ for _, pair in ipairs(map) do
11411141end
11421142
11431143print (table.concat (result , " \n " )) -- 使用 table.concat 将表元素连接成字符串
1144+
1145+ local function factorial (n ) -- 定义函数
1146+ if n == 0 then
1147+ return 1
1148+ else
1149+ return n * factorial (n - 1 )
1150+ end
1151+ end
1152+
1153+ print (" Factorial of 5 is " .. factorial (5 ))
11441154```
11451155
11461156#### Lua 模块 {#lua-modules}
11471157
1158+ 最简单的代码复用的方式是使用 ` loadfile() ` 函数直接加载另一个 Lua 脚本文件:
1159+
1160+ ``` lua
1161+ local f = loadfile (" some_script.lua" )
1162+ if f then
1163+ f () -- 执行加载的脚本
1164+ else
1165+ print (" Failed to load some_script.lua" )
1166+ end
1167+ ```
1168+
1169+ 但是这样做存在很多问题:每次调用 ` loadfile ` 都会重新加载,并且无法利用到 LuaJIT 的编译缓存机制。因此更推荐的做法是包装成 Lua 模块,然后使用 ` require ` 导入。以下是调用 cjson 模块解析 JSON 的示例:
1170+
1171+ ``` lua
1172+ -- 导入 cjson 模块用于处理 JSON
1173+ -- Debian 下包为 lua-cjson
1174+ local cjson = require " cjson"
1175+ local example = " {\" key1\" :\" value1\" ,\" key2\" :2}"
1176+ local decoded = cjson .decode (example )
1177+ print (decoded [" key1" ])
1178+ ```
1179+
1180+ 为了包装为模块,Lua 代码需要小幅修改。一个非常简单的模块示例如下:
1181+
1182+ ``` lua
1183+ local _M = {}
1184+
1185+ local function some_internal_func (a )
1186+ return a + a
1187+ end
1188+
1189+ function _M .f1 (a , b )
1190+ local aa = some_internal_func (a )
1191+ local bb = some_internal_func (b )
1192+ return aa + bb
1193+ end
1194+
1195+ return _M
1196+ ```
1197+
1198+ ### Nginx 中 Lua 的安装配置 {#lua-installation-configuration}
1199+
1200+ 要在 Nginx 中使用 Lua 脚本扩展能力的话,需要安装 Lua 模块。最简单的方式是使用 OpenResty,它集成了 Nginx 和 Lua 模块,并且预置了很多常用的第三方 Lua 库。如果不希望使用 OpenResty,也可以自行安装 Lua 模块(` libnginx-mod-http-lua ` 包)。安装此包后,` /etc/nginx/modules-enabled/ ` 会自动引入对应的配置:
1201+
1202+ ``` console
1203+ $ readlink /etc/nginx/modules-enabled/50-mod-http-lua.conf
1204+ /usr/share/nginx/modules-available/mod-http-lua.conf
1205+ $ cat /etc/nginx/modules-enabled/50-mod-http-lua.conf
1206+ load_module modules/ngx_http_lua_module.so;
1207+ ```
1208+
1209+ 与 ` sites-enabled ` 类似,` modules-enabled ` 目录下的配置文件会被 Nginx 主配置文件自动包含。配置后可以使用以下 ` location ` 测试:
1210+
1211+ ``` nginx
1212+ location / {
1213+ content_by_lua_block {
1214+ ngx.say("Hello, world!")
1215+ }
1216+ }
1217+ ```
1218+
1219+ 其中 [ ` content_by_lua_block ` ] ( https://github.com/openresty/lua-nginx-module?tab=readme-ov-file#content_by_lua_block ) 控制了请求的响应内容,而 [ ` ngx.say ` ] ( https://github.com/openresty/lua-nginx-module?tab=readme-ov-file#ngxsay ) 则会直接向响应中写入内容。
1220+
11481221## 示例介绍 {#examples}
11491222
11501223<!-- 以下给出一些实践中会使用的 Nginx 配置示例。
0 commit comments