最近上了一個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