LUA教程表达式逻辑运算符

Lua 中的逻辑操作符有 and, or, 以及 not。 和控制结构一样,所有的逻辑操作符把 false 和 nil 都作为假,而其它的一切都当作真。

and    or     not

逻辑运算符认为false和nil是假(false),其他为真,0也是true.

and和or的运算结果不是true和false,而是和它的两个操作数相关。

1a and b -- 如果a为false,则返回a,否则返回b 2a or b -- 如果a为true,则返回a,否则返回b

例子:

1print(4 and 5) --> 5 2print(nil and 13) --> nil 3print(false and 13) --> false 4print(4 or 5) --> 4 5print(false or 5) --> 5 6  7 10 or 20 --> 10 8 10 or error() --> 10 9 nil or "a" --> "a" 10 nil and 10 --> nil 11 false and error() --> false 12 false and nil --> false 13 false or nil --> nil 14 10 and 20 --> 20

一个很实用的技巧:如果x为false或者nil则给x赋初始值v

x = x or v

等价于:

1if not x then 2 x = v 3end

and的优先级比or高。
C语言中的三元运算符

a ? b : c

在LUA中可以这样来实现:

(a and b) or c

not的结果只返回false或者true

1print(not nil) --> true 2print(not false) --> true 3print(not 0) --> false 4print(not not nil) --> false

原文:LUA一个小巧脚本语言学习笔记

           LUA教程表达式逻辑运算符-10

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

thinkphp3.2.3模板渲染支持三元表达式

thinkphp3.2.3模板渲染支持三元表达式{$status?'正常':'错误'}{$info'status'?$info'msg':$info'error'}注意:三元运算符中暂时不支持点语法。如下:           <divclass"modalhidefade"id'myModa