Lua中的nil类型条件语句
2017-10-24 0:25:58
收藏:0
阅读:80
评论:1
问题
在 Lua 中:
local a = b or 0
local a = b and 1 or 0
其中,b 可以是任何类型。
这两行代码有何区别? 在什么情况下应该使用其中之一?
背景
我需要将现有的 Lua 代码移植到另一个服务中,并遇到了一个问题,即在代码的某些部分中(我不是 Lua 开发人员),一个变量被赋值为一个值,在代码的其他部分中,一个变量被赋值为另一个值。右侧的变量是一个输入参数,我无法确定其预期类型。
我尝试了什么
我在网上寻找了有关此问题的 Lua 文档,但找不到清晰的答案。我进行了自己的测试:
local a1;
print(type(a1)) -- nil
local b1 = a1 or 0
print(b1 .. " " .. type(b1)) -- 0 number
local c1 = a1 and 1 or 0
print(c1 .. " " .. type(c1)) -- 0 number
local a2 = 5
print(type(a2)) -- number
local b2 = a2 or 0
print(b2 .. " " .. type(b2)) -- 5 number
local c2 = a2 and 1 or 0
print(c2 .. " " .. type(c2)) -- 1 number
local a3 = 0
print(type(a3)) -- number
local b3 = a3 or 0
print(b3 .. " " .. type(b3)) -- 0 number
local c3 = a3 and 1 or 0
print(c3 .. " " .. type(c3)) -- 1 number
local a4 = false
print(type(a4)) -- boolean
local b4 = a4 or 0
print(b4 .. " " .. type(b4)) -- 0 number
local c4 = a4 and 1 or 0
print(c4 .. " " .. type(c4)) -- 0 number
local a5 = true
print(type(a5)) -- boolean
local b5 = a5 or 0
print(b5 .. " " .. type(b5)) -- 错误,将布尔类型连接到字符串
local c5 = a5 and 1 or 0
print(c5 .. " " .. type(c5)) -- 1 number
local a6 = "str"
print(type(a6)) -- string
local b6 = a6 or 0
print(b6 .. " " .. type(b6)) -- str string
local c6 = a6 and 1 or 0
print(c6 .. " " .. type(c6)) -- 1 number
local a7 = ""
print(type(a7)) -- string
local b7 = a7 or 0
print(b7 .. " " .. type(b7)) -- string
local c7 = a7 and 1 or 0
print(c7 .. " " .. type(c7)) -- 1 number
在我看来,and 条件语句的唯一用例是当 b 是布尔类型或 nil 类型,且当 b 为 nil 或 false 时,a 应该结果为0,当 b 为 true 时,a 应该结果为1。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

在 Lua 中,这些是选择运算符,具有短路求值。
false和nil是假值;任何其他值都是真值。除了 "假值 ",操作数类型并不重要,结果类型也不一定是"boolean"。or选择(返回)第一个真值操作数。and如果第一个操作数是假值,则选择第一个操作数,否则选择第二个操作数。它比or有更高的优先级。这导致了几个习惯用法:
b or 0 -- 默认值是 0 t = t or {} -- 存在或新的空表 b and 1 or 0 -- 强制转换为 1,否则默认为 0你两个示例之间的区别在于第二个强制转换为 1,而第一个则允许 "真值" b。