-
序
- 入门篇
- Lua 入门
-
Nginx
-
Nginx 新手起步
-
location 匹配规则
-
静态文件服务
-
日志
-
反向代理
-
负载均衡
-
陷阱和常见错误
- 环境搭建
-
Hello World
-
与其他 location 配合
-
获取 uri 参数
-
获取请求 body
-
输出响应体
-
日志输出
-
简单API Server框架
-
使用 Nginx 内置绑定变量
-
子查询
-
不同阶段共享变量
-
防止 SQL 注入
-
如何发起新 HTTP 请求
-
访问有授权验证的 Redis
-
select+set_keepalive 组合操作引起的数据读写错误
-
redis 接口的二次封装(简化建连、拆连等细节)
-
redis 接口的二次封装(发布订阅)
-
pipeline 压缩请求数量
-
script 压缩复杂请求
-
动态生成的 lua-resty-redis 模块方法
-
Nginx 新手起步
- LuaCjsonLibrary
- PostgresNginxModule
- LuaNginxModule
- LuaRestyDNSLibrary
- LuaRestyLock
- 测试
- Web 服务
- 火焰图
函数返回值
Lua 具有一项与众不同的特性,允许函数返回多个值。Lua 的库函数中,有一些就是返回多个值。
示例代码:使用库函数
string.find
,在源字符串中查找目标字符串,若查找成功,则返回目标字符串在源字符串中的起始位置和结束位置的下标。
local s, e = string.find("hello world", "llo")
print(s, e) -->output 3 5
copy
返回多个值时,值之间用“,”隔开。
示例代码:定义一个函数,实现两个变量交换值
local function swap(a, b) -- 定义函数 swap,实现两个变量交换值
return b, a -- 按相反顺序返回变量的值
end
local x = 1
local y = 20
x, y = swap(x, y) -- 调用 swap 函数
print(x, y) --> output 20 1
copy
当函数返回值的个数和接收返回值的变量的个数不一致时,Lua 也会自动调整参数个数。
调整规则: 若返回值个数大于接收变量的个数,多余的返回值会被忽略掉; 若返回值个数小于参数个数,从左向右,没有被返回值初始化的变量会被初始化为 nil。
示例代码:
function init() --init 函数 返回两个值 1 和 "lua"
return 1, "lua"
end
x = init()
print(x)
x, y, z = init()
print(x, y, z)
--output
1
1 lua nil
copy
当一个函数有一个以上返回值,且函数调用不是一个列表表达式的最后一个元素,那么函数调用只会产生一个返回值, 也就是第一个返回值。
示例代码:
local function init() -- init 函数 返回两个值 1 和 "lua"
return 1, "lua"
end
local x, y, z = init(), 2 -- init 函数的位置不在最后,此时只返回 1
print(x, y, z) -->output 1 2 nil
local a, b, c = 2, init() -- init 函数的位置在最后,此时返回 1 和 "lua"
print(a, b, c) -->output 2 1 lua
copy
函数调用的实参列表也是一个列表表达式。考虑下面的例子:
local function init()
return 1, "lua"
end
print(init(), 2) -->output 1 2
print(2, init()) -->output 2 1 lua
copy
如果你确保只取函数返回值的第一个值,可以使用括号运算符,例如
local function init()
return 1, "lua"
end
print((init()), 2) -->output 1 2
print(2, (init())) -->output 2 1
copy
值得一提的是,如果实参列表中某个函数会返回多个值,同时调用者又没有显式地使用括号运算符来筛选和过滤,则这样的表达式是不能被 LuaJIT 2 所 JIT 编译的,而只能被解释执行。