最近上了一个Lua/MoonScript的项目,第一次接触该语言,踩了一些坑,特此记录以为前车之鉴.
- 1.数组(table)下标默认从1开始,而不是0!!
严格来说,Lua中并没有所谓"数组(array)"的概念,取而代之的是表(table),其使用方法大概也与array差不多.
但需要注意的是,table的第一项下标为1,而不能想当然的认为是0;
table = {}
first = table[1]
- 2.井号“#”可以计算table的长度,但是对post的form无效,无论form内容为何,计算结果始终为0;
form 的本体也是table无误,但是使用#计算长度时返回值总是0,原因不明;
对此我的解决方式是手动封装一个table长度计算方法count:
count: (table={}) =>
count = 0
for key,value in pairs(table)
count += 1
count
- 3.使用星号" * "对循环中的table项直接unpack:
官方文档中对于星号" * "的解释为:
Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop:
tuples = {
{"hello", "world"}
{"egg", "head"}
}
for {left, right} in *tuples
print left, right
We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure.
- 4.同C语言一样,使用三个点号(period) " ... "表示可变参数:
test: (table, ...) =>
ngx.say(...)
table = {}
@test table, '+', '1', 's'
ngx.exit(ngx.HTTP_OK)
-- 结果: +1s
- Lua中的for循环没有所谓的
continue
语法,原因是因为其设计者觉得不必要,可以用其他方法替代...
- Lua中的for循环没有所谓的
Our main concern with "continue" is that there are several other control structures that (in our view) are more or less as important as "continue" and may even replace it. (E.g., break with labels [as in Java] or even a more generic goto.) "continue" does not seem more special than other control-structure mechanisms, except that it is present in more languages. (Perl actually has two "continue"statements, "next" and "redo". Both are useful.
不过确实可以用麻烦一点的方法变相实现这个功能:
for k, v in pairs data
while true do
if conditions
break
- 6.所有变量建议先声明后使用,不要继承PHP随写随用的坏习惯,否则可能被默认赋值为空.
比如下例中:
flag = '1'
if flag == '1'
result = '2'
else
result = '3'
@var_dump result
此时result的输出结果为{}
,其type为nil
,而应该写为:
flag = '1'
result = ''
if flag == '1'
result = '2'
else
result = '3'
@var_dump result
7.不同版本的ngx-lua-db模块可能会在
execute
时产生不一样的编译结果,导致程序运行失败.所以建议在开发环境,测试环境和生产环境均使用相同的各模块版本.8.在某种条件下服务器的异常终止可能会导致重连时db进程被阻塞,导致db无法被正确加载,接口返回错误500,log中无任何记录.此时重启nginx会解决问题,具体原因和解决方式还在研究中.
顺便上一个经常用的到的Lua Math库:
http://blog.csdn.net/goodai007/article/details/8076141