1. 程式人生 > >Lua語法學習筆記

Lua語法學習筆記

  1. 註釋符–
  2. nil 表示變數還沒有賦值。如果給一個變數賦值為nil,表示刪除該變數。
  3. Number:Lua中數字只有雙精度型別,不區分浮點和整型。
  4. 區域性變數用local宣告,Lua預設變數是全域性的。
  5. 不等於~=
  6. while和repeat

    indx = 1
    while indx < 10 do
        indx = indx + 1
    end
    
    repeat
        indx = indx + 1
    until indx > 10
  7. for語句:Lua中的for語句迴圈次數在第一次就確定了,後面不改變

    for indx = 1,10 do
        print(indx)
    end
    
    for
    indx = 1,10,-1 do print(indx) end
  8. 函式

    function SetName(myString)
    
    end
    
    function SetName(...)
        if arg.n >0 then
            for indx = 1,arg.n do
            local myString = string.format("%s%d","Argument ",indx,":")
            end
        else
            print(myString,arg[indx]);
        end
    end
    
    function Multiply
    (val1,val2,...)
    local myString if arg.n == 0 then myString = string.format("%d%s%d%s%d",val1,"*",val2,"=",val1*val2) else local val3 = val1*val2*arg[1] myString = tring.format("%d%s%d%s%d%s%d",val1,"*",val2,"*",arg[1],"=",val3) end print(myString) end
  9. 返回值return

    function TimesTwo(myValue)
        myValue = myValue*2
        return myValue
    end
    
    a = 24 + TimesTwo(12)
    print(a)
    
    function ThreeDice()
        d1 = math.random(1,6)
        d2 = math.random(1,6)
        d3 = math.random(1,6)
        myTotal = d1 + d2 +d3
        return d1,d2,d3,myTotal
    end
    
    a,b,c,d = ThreeDice()
  10. assert函式

    a = "hello world"
    b = "print(a)"
    assert(loadstring(b))()

    輸出:
    helloworld

  11. math.floor:向下取整,四省五入的話先加0.5在向下取整
  12. math.random()

    myDie = math.random(1,6)
    --設定隨機數發生種子
    \math.randomseed(os.date(%d%H%M%S))
  13. math.min():判斷table裡的資料最小值,與loadstring配合

    myTable = {7,1,13,6,89,4,56,2,54,6}
    function GetMin(theTable)
        myString = "myValue = math.min("
        for index,value in ipairs(theTable) do
            myString = string.format("%s%d%s", myString, value, ",")
        end
        --remove final comma
        myString = string.sub (myString, 1, string.len(myString) - 1)
        myString = string.format("%s%s", myString, ")")
        loadstring(myString)() --run the chunk
        print(myString) -- see the string
        print(myValue) --see the result
        return myValue
    end
  14. tonumber()
    tostring()
    string.char(10)換行
    string.len()
    string.sub(myString,start,end)擷取子串,start可以為負數,從末尾開始擷取string.sub(myString,start)
    string.format(“%d..”,int,..)
    string.find(myString,”…”)
    eg:
    myString = “My name is John Smith”
    sStart,sEnd = string.find(myString,”John”)
    print(sStart,sEnd)–12,15
  15. 字元和格式:

    myString = "The price is $17.50."
    filter = "$%d%d.%d%d"
    print(string.sub(myString,string.find(myString,filter)))
    --$17.50
    string.gsub(sourceString,pattern,replacementString)
    --返回一個字串,sourceString字元中,滿足pattern格式的字元都會被替換成replacementString引數的值
    eg:
    
    myString = "My name is John Smith. My phone is 555-3257"
    newString = string.gsub(myString,"%d","*")
    --My name is John Smith. My phone is ***-***
    
    a = "(309) 555-1234"
    print(string.gsub(a,"%(%d%d%d%)","(781)"))
    --(781) 555-1234
    
    a = "happy, hello, home, hot, hudson"
    print(string.gsub(a,"h%a+","An H world!",2))
    --An H world!, An H world!, home, hot, hudson
    --查詢以h開頭的字元,%a+表示任意長度的字母,並在遇到空格和標點符號時為止,最後的引數2表示只替換最先遇到的兩個
    
    string.gfind(string,pattern)注意是遍歷字串,只要滿足指定格式就返回該子串
    a = "This is my rather long string."
    for v in string.gfind(a,"%a+") do
        print(v)
    end
    --This
      is
      my
      rather
      long
      string
  16. table資料結構
    table.getn()
    table.sort()

    --sort有可選的引數, 此引數是一個外部函式, 可以用來自定義sort函式的排序標準.此函式應滿足以下條件: 
    --接受兩個引數(依次為a, b), 並返回一個布林型的值, 當a應該排在b前面時, 返回true, 反之返回false.
    --下面是一個逆序排序,當direction=1時逆序
    function Sort(theTable, direction)
        if direction ~= 1 then
            table.sort(theTable)
        else
            function Reverse(a, b)
                if a < b then
                    return false
                else
                    return true
                end
            end
            table.sort(theTable, Reverse)
        end
    end
    table.insert(myTable,position,value)預設是末尾
    table.remove(myTable,position) 預設是末尾,且返回去除值
    
    多維table
    
    widget = {}
    widget.name = {}
    widget.cost = {}
    widget.name[1] = "Can opener"
    widget.cost[1] = "$12.75"
    widget.name[2] = "Scissors"
    widget.cost[2] = "$8.99"
    pairs():遍歷table中的每一個元素
    
    myName = {"Fred","Ethel","lucy","Ricky"}
    for index,value in pairs(myName) do
        print(index,value)
    end
    
    for index = 1,table.getn(myNames) do
        print(index,myName[index])
    end
    
  17. I/O基礎

    利用io可以生成可執行的lua檔案,可以用於遊戲資料或者遊戲進度的儲存
    
    myFile = io.open("xxx.lua","w")--檔案不存在則新建 w代表寫入
    if myFile ~= nil then
        myFile:write("--Test lua file")
        myFile:write(string.char(10))--換行
        myFile:write(string.format("%s%s","--File created on:",os.date()))
        myFile::write("print(\"helloworld!\")")
        io.close(myFile)
    end