且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])

更新时间:2022-02-12 05:24:39

多变量赋值

--多变量赋值
a,b,c='123',666,true
print(a)
print(b)
print(c)

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])
这语言是真的骚,全自动赋值
变量少了,自动补空

--全自动赋值
--变量少了,自动补空
t1,t2,t3=1,2
print(t1)
print(t2)
print(t3)

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])

--变量多了,自动裁剪
t1,t2,t3=1,2,6,7,8
print(t1)
print(t2)
print(t3)

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])

函数多返回值

--多返回值赋值
function Test()
    return 1,2,3,4
end

--获得返回值也是一样的,全自动的,多退少补
a,b,c=Test()
print(a)
print(b)
print(c)
print('-------------------------------')
a,b,c,d,e,f=Test()
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])

and or(在lua内的逻辑运算符)

逻辑与或
and or 不仅可以与bool 其他任何东西也可以连


--lua中 只有 nil\false 才认为是假
--'短路'   对于and来说 有假则假   or来说 有真则真
--因此 只需要判断第一个是否满足 就会停止判断
print(1 and 2) --因为只有 nil\false 才认为是假,所以程序会继续执行到2
print(0 and 1) --同上
print(nil and 1) --因为只有 nil\false 才认为是假,所以程序停止执行下一个,返回nil

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])

--or测试
--遇真则真,遇到真就不会再去计算后面的值了
print(1 or 2)
print(0 or 1)
print(nil or 1)

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])
用lua 逻辑运算符实现三目运算

--lua虽然不支持三目运算符
--但我们可用lua 逻辑运算符实现
x=3
y=2
res = (x>y) and x or y
print(res)
--(x>y) and x -> x    and遇假则假
--x or y -> x         or遇真则真


x=1
res = (x>y) and x or y
print(res)
--(x>y)and x ->(x>y)
-- (x>y) or y -> y   (x>y)返回的是false(假) , or遇真则真,所以返回y

lua 特殊用法(多变量赋值、函数多返回值、and or[短路])
lua 特殊用法(多变量赋值、函数多返回值、and or[短路])