Lua语言中的“惊喜”
source link: https://z-rui.github.io/post/2015/02/lua-surprises/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Lua在有些地方没有采用其他语言(尤其是C)的约定俗成,所以经常给程序编写者带来惊喜(surprise, “gotcha”)。根据我的经验,整理如下:
- 不等号是
~=
,而不是!=
。
- 这是我写Lua程序时最常犯的一个笔误。只能说,几乎所有的程序语言,不等号用的都是
!=
(C家族),还有一部分用<>
(Pascal, Basic, SQL)。用~=
真的只有Lua一家。
- 未用
local
声明的变量名都是全局变量。引用未定义的全局变量,得到的值是nil
。
- 这是我写Lua程序时bug的主要来源。Lua默认措施不利于排查无意中的错误,例如变量名的拼写错误。
- 使用一个称为
strict
的模块有助于防止产生这方面的问题。
- 使用for语句循环一个表时,在
in
关键字后面必须是pairs
或者ipairs
。简单的for x in tablename
是不对的。
- 这个问题主要来自Python带来的习惯:
for x in seq:
- 如果
s = "Hello, world"
,则s[5]
的值是nil
。
- 字符串不能通过下标操作获得某个位置的字节。这是一个大的惊喜,因为给字符串做下标操作看起来在自然不过了。
- 如果想这么做,使用
s:sub(5, 5)
。(有点丑,尤其是当下标不是一个常数而是一个复杂的表达式时。)
- 表的起始下标默认是1,而不是0。
- 这主要困扰C语言的使用者。以1作为起始下标其实并不是特别别扭的事,对C语言的重度使用者除外。
- 与此相呼应,通常区间将表示为闭区间,而不是像以0作为起始下标时那样,表示为左闭右开区间。请参见Dijkstra的文章。
- (Lua 5.3) 异或运算的符号是
~
,而不是^
。
- 事实上,
^
是乘方的符号。在一些计算器以及电子试算表软件中,这个符号的确表示乘方。但是,C语言程序员仍然表示不服。(C语言没有乘方运算符。Python尊重C的约定,使用^
表示异或运算,而**
表示乘方(这个符号来自Fortran)。) - 单目运算符按位取反的符号也是
~
,这和C语言的约定一致。有趣的是,Go语言和Lua恰好相反:在Go中,异或运算和按位取反的符号都是^
,~
符号未被使用。
- 没有
continue
。
Recommend
-
139
Notepad++配置lua环境
-
61
-
79
我们能用lua做什么
-
49
This is a rather old post I originally wrote in 2013, but it’s still a good introduction to Lua and Nmap scripting, so I decided to repost it. Whether you are working as a security professional or a network admi...
-
44
上次在 blog 上写 Lua GC 是 2011 年,lua 5.2 尚未发布时候的事情了。我认为仔细研读优秀开源代码是非常值得做的事情,但把研读过程写出来却意义不大。代人咀...
-
108
单个 Lua 虚拟机只能工作在一个线程下,如果你需要在同一个进程中让 Lua 并行处理一些事务,必须为每个线程部署独立的 Lua 虚拟机。 ps. 在少量多线程应用环境,加锁也是可行的。你可以在编译时自定义 lua_lock...
-
43
WARNING! Please expect breaking changes and unstable APIs. Most of them are currently at an early, experimental stage. Contributing This project welcomes contributions and suggestions. Most contribut...
-
52
关键字: and break do else elseif end false for function if in local nil not or repeat return then true until while Lua 中约定: 以下划线开头, 后接大写字母的为保留的全局变量. 例如...
-
85
Croissant A Lua REPL and debugger implemented in Lua
-
0
在Lua语言中,可以使用require函数来加载模块和运行库,用于调用其他文件中的方法。 0x01 require函数的使用方法-- 文件名为 test_module.lua-- 定义一个名为 module 的模块module = {}-- 定义一个常...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK