Lua MoonScript 使用注意事項(xiàng)

最近上了一個(gè)Lua/MoonScript的項(xiàng)目,第一次接觸該語言,踩了一些坑,特此記錄以為前車之鑒.

  • 1.數(shù)組(table)下標(biāo)默認(rèn)從1開始,而不是0!!
    嚴(yán)格來說,Lua中并沒有所謂"數(shù)組(array)"的概念,取而代之的是表(table),其使用方法大概也與array差不多.
    但需要注意的是,table的第一項(xiàng)下標(biāo)為1,而不能想當(dāng)然的認(rèn)為是0;
table = {}
first = table[1]
  • 2.井號(hào)“#”可以計(jì)算table的長度,但是對(duì)post的form無效,無論form內(nèi)容為何,計(jì)算結(jié)果始終為0;
    form 的本體也是table無誤,但是使用#計(jì)算長度時(shí)返回值總是0,原因不明;
    對(duì)此我的解決方式是手動(dòng)封裝一個(gè)table長度計(jì)算方法count:
count: (table={}) =>
    count = 0
    for key,value in pairs(table)
        count += 1
    count
  • 3.使用星號(hào)" * "對(duì)循環(huán)中的table項(xiàng)直接unpack:
    官方文檔中對(duì)于星號(hào)" * "的解釋為:

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語言一樣,使用三個(gè)點(diǎn)號(hào)(period) " ... "表示可變參數(shù):
test: (table, ...) =>
    ngx.say(...)
table = {}
@test table, '+', '1', 's'

ngx.exit(ngx.HTTP_OK) 
-- 結(jié)果: +1s
    1. Lua中的for循環(huán)沒有所謂的continue語法,原因是因?yàn)槠湓O(shè)計(jì)者覺得不必要,可以用其他方法替代...

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.

不過確實(shí)可以用麻煩一點(diǎn)的方法變相實(shí)現(xiàn)這個(gè)功能:

for k, v in pairs data
    while true do
        if conditions
            break
  • 6.所有變量建議先聲明后使用,不要繼承PHP隨寫隨用的壞習(xí)慣,否則可能被默認(rèn)賦值為空.
    比如下例中:
    flag = '1'
    if flag == '1'
        result = '2'
    else
        result = '3'

    @var_dump result

此時(shí)result的輸出結(jié)果為{},其type為nil,而應(yīng)該寫為:

    flag = '1'
    result = ''
    if flag == '1'
        result = '2'
    else
        result = '3'

    @var_dump result
  • 7.不同版本的ngx-lua-db模塊可能會(huì)在execute時(shí)產(chǎn)生不一樣的編譯結(jié)果,導(dǎo)致程序運(yùn)行失?。越ㄗh在開發(fā)環(huán)境,測(cè)試環(huán)境和生產(chǎn)環(huán)境均使用相同的各模塊版本.

  • 8.在某種條件下服務(wù)器的異常終止可能會(huì)導(dǎo)致重連時(shí)db進(jìn)程被阻塞,導(dǎo)致db無法被正確加載,接口返回錯(cuò)誤500,log中無任何記錄.此時(shí)重啟nginx會(huì)解決問題,具體原因和解決方式還在研究中.

順便上一個(gè)經(jīng)常用的到的Lua Math庫:
http://blog.csdn.net/goodai007/article/details/8076141

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容