Lua学习笔记-判断是否是布尔型

1、如何在在不使用type函数的前提下判断是否是布尔型

代码如下:

-- Exercise 3.5: How can you check whether a value is boolean
-- without using the type function?

-- check if a variable is a boolean
-- comparisons are false if the types are different
function is_boolean(v) return v == true or v == false end
--当v为真的时候,v==true为true,v==false为false,or的结果为v==true,即为真
--当v为假的时候,v==true为false,v==false为true,or的结果为v==false,即为false
-- test the function with some examples
num = 123
str = "str"
bool = true

print("is_boolean(123)   --> " .. (is_boolean(num) and "true" or "false"))
print("is_boolean('str') --> " .. (is_boolean(str) and "true" or "false"))
print("is_boolean(true)  --> " .. (is_boolean(bool) and "true" or "false"))

-- print("is_boolean(123)   --> " .. is_boolean(num))--这种方式是错的,因为..字符串的连接符是无法将布尔型和字符串进行连接的
-- print("is_boolean('str') --> " .. is_boolean(str))--为实现打印出“true”<span style="display: none; width: 0px; height: 0px;" id="transmark"></span>和“false”字符串使用上述的方式
-- print("is_boolean(true)  --> " .. (is_boolean(bool)))

2、类似的可以计算两个数的最大值:

代码:

function mymax(x,y)
	return x>y and x or y
--当x>y为true时,x>y and x结果为x(x为数字,必为true),x or y结果为x,即为true
--当x>y为false时,x>y and x结果为x>y,即为false,再进行x>y or y,此时结果为y
end
print("max(3,5):"..(mymax(3,5)))
print("max(10,15):"..(mymax(10,15)))

附录:

运算符的优先级如下(从高到低)
从高到低的顺序:
^                             
not     - (unary)  --单元运算符                     
*     /                       
+     -                       
..                             
<     >     <=     >=     ~=     ==
and                             
or                             
除了 ^和 .. 外所有的二元运算符都是左连接,左连接,左连接的,重要事情要说三遍。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值