天天看點

Lua程式設計

一.lua環境安裝

1.SciTE安裝包

Github 下載下傳位址:https://github.com/rjpcomputing/luaforwindows/releases

2.LuaDist(官方推薦,但不是很好用)

http://luadist.org/

二.lua中的注釋

1.單行注釋--

--這裡是單行注釋      

2.多行注釋

--[[
這裡是多行注釋
]]--      

小技巧:在多行注釋中,--[[添加一個短橫線變成---[[就可以取消多行注釋

三.标示符命名規則

使用大小寫字母或下劃線開頭,加上0個或若幹個大小寫字母、數字或下劃線。

注意:lua中内部全局變量基本使用下劃線加上大寫字母命名,是以不推薦這種方式命名标示符,避免沖突。

四.lua中的資料類型

1.資料類型nil

lua中的空值類型,删除變量時将變量設定為nil值即可。沒有聲明的變量的值都是nil。

b = 1
print(b)
b = nil
print(b)      
Lua程式設計

 2.資料類型boolean

布爾值隻有兩個值true和false,表示真和假。值得注意的是,lua中在作邏輯判斷時(如分支結構或循環結構中的真假判斷),false和nil都視為假,true和其他值都視為真。

if nil then
    print(' ')
else
    print(false)
end

if 1 then
    print(true)
end      
Lua程式設計

 3.資料類型number

lua中的數字都是number類型,可以了解為就是c中的double類型。number有如下寫法:

print(2)
print(2.2)
print(2e3)
print(2.34e5)
print(3.1e-2)      
Lua程式設計

 4.資料類型string

字元串類型使用單引号或雙引号引用都可以,也可以使用兩個中括号[[]]來引用字元串。

print('我是字元串')
print("我是字元串")
print([[我是字元串]])      
Lua程式設計

 字元串的拼接使用..,不能使用+号。

print('lua中的+号會自動将'..'字元串兩邊的字元串轉化為數字')
print('2'..3)
print('2'+'3')
print(2+3)
print('2'+3)
print('2+3')
print('a'+3)      
Lua程式設計

 使用#獲得字元串的位元組數。

print(#'aaa aa')
print(#'中文一個字元占用兩個位元組')      
Lua程式設計

 5.資料類型table

表的構造和基本使用。當定義table時直接定義值,不定義鍵時,table和string一樣,可以使用#獲得table中值的個數(本質上是取得最大索引)。

tab1 = {}  --空表  {}構造表達式
tab2 = {key1='value1',key2='value2'}  --使用鍵值對的形式構造表(和map或dictionary等類似)
tab3 = {'value1','value2','value3'}  --直接給出表的值,預設索引為1,2,3,4...,和數組或list等的性質類似

print(tab1)  --直接列印表,列印的是表的位址
print(tab1.key)  --表中沒有的鍵對應值為nil

print(tab2.key1)  --擷取表中的某個索引對應值的方法一
print(tab2['key1'])  --擷取表中某個索引對應值的方法二

print(tab3[2])  --沒有給出索引的表預設索引是1,2,3,4...,不能使用方法一擷取索引對應的值
print(tab3['1'])  --索引的類型是number,使用字元1進行取值不能取得值

--使用循環周遊表
for k,v in pairs(tab3) do
    print(k..':'..v)
end      
Lua程式設計

 表的添加值

tab = {}
tab.key1 = 'value1'
tab.key2 = 'value2'  --索引是字元串使用.指派,使用中括号指派會報錯
tab[10] = 100  --索引是number及其他類型使用中括号進行指派,使用.指派同樣報錯。nil不能作為索引。
tab[false] = 10

print(tab.key1)  --同樣的,在擷取值時也需要注意取值的方式
print(tab[key2])
print(tab[10])
print(tab[false])      
Lua程式設計

 6.資料類型function

使用function定義函數,不需要傳回值,參數也不需要定義類型。

function fact(n)
    if n==1 then
        return n
    else
        return n*(fact(n-1))
    end
end

print(fact(4))      
Lua程式設計

 函數同樣可以作為值進行傳遞。

function fact(n)
    if n==1 then
        return n
    else
        return n*(fact(n-1))
    end
end

print(fact(4))

fact2 = fact

print(fact2(5))      
Lua程式設計

 函數也可以作為參數傳遞,甚至可以定義匿名函數(類似于委托)。

--定義測試函數
function testFun(tab,fun)
    for k,v in pairs(tab) do
        fun(k,v)
    end
end

--定義表和參數中的函數
tab = {key1='value1',key2='value2'}
function f(k,v)
    print(k..':'..v)
end

--調用測試函數
testFun(tab,f)      
Lua程式設計
--定義測試函數
function testFun(tab,fun)
    for k,v in pairs(tab) do
        fun(k,v)
    end
end

--定義
tab = {key1='value1',key2='value2'}

--調用測試函數,以匿名函數的形式傳遞函數參數
testFun(tab,
    function (k,v)
        print(k..' '..v)
    end
)      
Lua程式設計

 7.資料類型thread

thread(線程)本質上是協程。

8.資料類型userdata

userdata是使用者自定義的資料類型,通常由C/C++建立。

五.文法

1.全局變量和局部變量

lua中的變量不需要聲明類型,預設情況下,變量都是全局變量。可以使用local關鍵字聲明局部變量,局部變量隻在目前代碼塊中起作用。一般情況下, 通路局部變量的速度更快。

function test()
    a = 5
    local b = 6
end

test()

print(a)
print(b)      
Lua程式設計

 2.變量的指派

變量可以單個指派,也可以多個同時指派,指派的資料類型也可以不同。也可以使用多變量指派友善地交換變量的值。

--可以單變量指派,也可以多變量指派
a = 1
a,b = 1,2
a,b,c = 1,'a',3

print(a,b,c)

--交換兩個變量的值
a,b = b,a
print(a,b,c)

--交換三個變量的值
a,b,c = c,a,b
print(a,b,c)

--變量的個數多于值,多出來的變量會被自動忽略;值的個數多于變量,多出來的值會被自動忽略
c,d,e = 1,2
f,g = 4,5,6
print(c,d,e,f,g)      
Lua程式設計

 3.循環

while循環。

i = 1
while i<=5 do
    print(i)
    i=i+1
end      
Lua程式設計

 for循環。之前也有用到過周遊表的for循環,類似于foreach的使用。

--i從1自增到5,每次自增1
for i=1,5 do
    print(i)
end

--i從1自增到10,每次自增2
for i=1,10,2 do
    print(i)
end      
Lua程式設計

 repeat until循環。這個循環相當于do...while,但是和do...while有所不同。do...while是先執行一次do中的代碼塊,再判斷while的邏輯語句,如果滿足條件繼續執行;repeat until是先執行一次until中的代碼塊,再判斷until中的邏輯語句,如果不滿足條件繼續執行。

i = 1
repeat
    print(i)
    i=i+2
until i>10      
Lua程式設計

 4.分支結構

--if語句
if 0 then
    print(0)
end

--if else語句
i = 1
if i<=0 then
    print(0)
else
    print(1)
end

--if else if ...語句
j = -2
if j <0 then
    print(-1)
elseif j==0 then
    print(0)
else
    print(1)
end      
Lua程式設計

 注:循環結構和分支結構中的,while、for、if等語句後面跟上邏輯語句,這些邏輯語句可以使用括号括起來,也可以使用空格隔開,不使用括号,這裡都沒有使用括号。

 5.函數

在lua中,函數可以作為資料指派,也可以作為參數傳遞。

local function max(num1,num2)
    if num1 < num2 then
        return num2
    else
        return num1
    end
end

print(max(3,-5))

--函數作為資料指派
temp = max
print(temp(1,8))

myprint = function (param)
    print('this is my print function '..param)
end

myprint('ww')

--函數作為參數傳遞
function add(num1,num2,printFun)
    res = num1+num2
    printFun(res)
end

add(40,50,myprint)

--lua中的函數可以傳回多個值
function temp()
    return 10,20,30,40
end

res1,res2,res3,res4 = temp()
print(res1,res2,res3,res4)

--lua中的函數參數個數可變,如print函數
--...代表可變的參數,這些參數會被封裝為一個名稱為arg的表,使用表的方式通路這些參數,在使用for循環周遊表時arg會多一個值表示參數個數
--可變參數前可以有其他參數,但是可變參數一定在參數清單的最後,封裝時隻有可變參數部分會被封裝到表arg中
function test(a,...)
    for k,v in pairs(arg) do
        print(v)
    end
end

test(1,2,3)      
Lua程式設計

 六.lua中的運算符

1.算數運算符+、-、*、/、%、^(幂運算符在c#語言中不存在,c#中使用函數求幂)

2.關系運算符==、~=(不等于、 <、>、<=、>=

3.邏輯運算符and、or、not

print(3>2 and 4>3)
print(false or false)
print(not true)      
Lua程式設計

 七.lua中的常見API

1.string有關的API

常見轉義字元:\n 換行、\\ 一個反斜杠、\" 雙引号、\' 單引号

a = 'hello\n\world my name is \'Micheal\''
print(a)      
Lua程式設計

string.upper 将字元串轉換為全部大寫 string.lower 将字元串轉化為全部小寫

str = 'Hello everybody'
str2 = string.upper(str)
print(str,str2)
str3 = string.lower(str)
print(str,str3)      
Lua程式設計

 string.gsub 将指定的字元替換為其他指定的字元

str = 'Hello everybody'
--将str中的字元e替換為字元8
str2 = string.gsub(str,'e','8')
print(str,str2)
--将str中的字元e替換為字元123,最多替換1次
str3 = string.gsub(str,'e','123',1)
print(str,str3)      
Lua程式設計

 string.find 查找指定字元的第一個索引

str = 'Hello everybody'

--從頭查找'every'字元的索引(索引從1開始)
index = string.find(str,'every')
print(index)
--從第6個字元開始茶軸'o'字元的索引
index2 = string.find(str,'o',6)
print(index2)      
Lua程式設計

 string.reverse 反轉字元串

str = 'Hello everybody'

str2 = string.reverse(str)
print(str2)      
Lua程式設計

 string.format 字元串格式化輸出(未知number使用%d代替,未知string使用%s代替,其他代替格式可以自行查閱)

num1 = 5
num2 = 10
str = string.format('加法:%d+%d=%d',num1,num2,num1+num2)
print(str)
date,month,year = 30,1,2021
d = string.format('日期:%02d/%02d/%03d',date,month,year)
print(d)      
Lua程式設計

 string.char 将指定的數字轉化為對應字元 string.byte 将字元轉化為數字(預設轉化字元串第一個字元,也可以指定轉化第幾個字元)

print(string.char(97,98,99,100))
print(string.byte('abcd'))
print(string.byte('abcd',3))      
Lua程式設計

 string.len 獲得指定字元串的長度(和#的結果相同)

print(string.len('我有一個夢想'))      
Lua程式設計

 string.rep 得到指定字元串重複指定次後的字元串

print(string.rep('我有一個夢想',5))      
Lua程式設計

 string.gmatch 正規表達式比對,傳回一個疊代器

for word in string.gmatch('Hello lua user','%a+') do
    print(word)
end      
Lua程式設計

 2.table有關的API

lua中array本質上是table。因為table是動态的,是以lua中的array也是動态的。值得注意的是,table中的預設索引是從1開始的,是以array中的預設下标也是從1開始的。下面是一個二維數組的例子:

array = {}
for i=1,4 do
    array[i] = {}
    for j=1,3 do
        array[i][j]=i*j
    end
end

for i=1,4 do
    for j=1,3 do
        print(array[i][j])
    end
end      
Lua程式設計

 數組的周遊。

array = {'lua','c#','java'}

--疊代函數一pairs:周遊table中的key和value
for k,v in pairs(array) do
    print(k,v)
end

--疊代函數二ipairs:從索引1開始,遞增周遊,遇到nil就停止
for k,v in ipairs(array) do
    print(k,v)
end

array[2] = nil

for k,v in ipairs(array) do
    print(k,v)
end      
Lua程式設計

表可以當作引用類型使用,表指派給其他表指派的是位址引用。

table = {'a','b','c'}
newtable = table

print(table[2])
print(newtable[2])

newtable[2] = 'd'

print(table[2])
print(newtable[2])      
Lua程式設計

 表的資料拼接。

table1 = {'a','b','c'}

--直接拼接
str = table.concat(table1)
print(str)

--使用,間隔開拼接的資料
str = table.concat(table1,',')
print(str)

--使用,間隔開資料,指定拼接的索引
str = table.concat(table1,',',2,3)
print(str)      
Lua程式設計

 表的資料插入和移除。

table1 = {'lua','c#','java','php'}
print(table.concat(table1,','))

--直接插入到末尾
table.insert(table1,'javascript')
print(table.concat(table1,','))

--指定插入到哪一位,後面的資料依次向後移動一位
table.insert(table1,2,'c++')
print(table.concat(table1,','))

--移除表一位資料
table.remove(table1)
print(table.concat(table1,','))

--移除指定位置的資料
table.remove(table1,3)
print(table.concat(table1,','))      
Lua程式設計

表的排序。

table1 = {'lua','c#','java','php','c++','javascript'}
print(table.concat(table1,','))

--排序,按照ASCII碼表順序排列
table.sort(table1)
print(table.concat(table1,','))      
Lua程式設計

八.面向對象程式設計及其他特性

1.子產品與包

lua中的子產品相當于c#的命名空間或java的包。

--定義子產品,這個子產品儲存為檔案Module.luavar = 'movin'

func1 = function()
    print('這是一個函數')
end

return module      
--引入子產品
require 'Module'

--使用子產品中的變量
print(var)
func1()      
Lua程式設計

 lua中的包是指使用C包,lua和C很容易結合,lua就是使用C寫成的。

2.元表

lua提供了元表允許我們改變table的行為,每種行為關聯了對應的元方法。

mytable = {'lua','java','c#','c++'}  --普通表
mymetatable = {}  --元表  拓展了普通表的行為
mytable = setmetatable(mytable,mymetatable)  --關聯元表和普通表      

1)__index元方法,這是metatable中最常用的鍵。當通過鍵通路table的時候,如果這個鍵沒有值,那麼lua就會尋找該table的metatable中的__index鍵。如果__index包含一個表格,lua會在表中查找相應的鍵,如果__index包含一個函數,lua就會調用那個函數。

mytable = {'lua','java','c#','c++'}

mymetatable = {
__index=function (tab,key)
    return 'javascript'
end
}

mytable = setmetatable(mytable,mymetatable)

print(mytable)
print(mymetatable)  --表和元表關聯,但是兩個表并不相同,元表是表的拓展
print(mytable[1])  --存在的鍵值
print(mymetatable[1])
print(mytable[10])  --不存在的鍵值,調用元表中__index鍵對應的函數
print(mymetatable[10])      
Lua程式設計

 2)__newindex元方法,當對表的新索引進行指派時會起作用,并且會取消指派操作。

mytable = {'lua','java','c#','c++'}

mymetatable = {
__newindex = function (tab,key,value)
    print(string.format('我們要修改的key為%s,value為%s',key,value))
end
}

mytable = setmetatable(mytable,mymetatable)

--下面這些操作都不會觸發__newindex對應的方法
mytable[1] = 'javascript'
print(table.concat(mytable,'  '))
table.insert(mytable,'lua')
print(table.concat(mytable,'  '))
table.insert(mytable,3,'c')
print(table.concat(mytable,'  '))
table.remove(mytable,1)
print(table.concat(mytable,'  '))
table.remove(mytable)
print(table.concat(mytable,'  '))

mytable[5] = 'lua'  --對新索引進行指派時會調用__newtable對應的方法,而且不會進行指派操作
print(table.concat(mytable,'  '))      
Lua程式設計
mytable = {'lua','java','c#','c++'}

mymetatable = {
__newindex = function (tab,key,value)
    rawset(tab,key,value)  --由于調用了__newindex對應的函數後不會進行指派,若想指派,可以使用rawset函數(如果直接指派會産生死循環)
    --mytable[5] = 'lua'  這裡采用這種方式指派會産生死循環
end
}

mytable = setmetatable(mytable,mymetatable)


mytable[5] = 'lua'  
print(table.concat(mytable,'  '))      
Lua程式設計
mytable = {'lua','java','c#','c++'}

newtable = {}
mymetatable = {
__newindex = newtable  --__newindex對應的是一個表
}

mytable = setmetatable(mytable,mymetatable)


mytable[5] = 'javascript'   --設定不存在的索引的值時會設定到__newindex對應的表中

print(mytable[5])
print(newtable[5])  --在__newindex對應的表中,索引值還是5      
Lua程式設計

 3)操作符元方法。

mytable = {'lua','java','c#','c++'}

mymetatable = {
__add = function(tab,newtab)  --__add索引的值定義了表的加法操作,這裡将第二個相加的表的所有鍵值對拼接到第一個表的最後
    for k,v in pairs(newtab) do
        table.insert(tab,v)
    end

    return tab
end
}

mytable = setmetatable(mytable,mymetatable)

newtable = {'python','php'}

print(table.concat(mytable+newtable,' '))      
Lua程式設計

除了__add外,對應其他運算的元方法有:__sub(減法)__mul(乘法)__div(除法)__mod(求模)__pow(乘方)__unm(取負)__concat(連接配接)__eq(是否相等)__lt(小于)__le(小于等于)

 4)__call元方法

将表當作函數調用時調用__call對應的函數。

mytable = {'lua','java','c#','c++'}

mymetatable = {
__call = function(tab,arg)
    print(arg)
end
}

mytable = setmetatable(mytable,mymetatable)

mytable('我是大帥比')      
Lua程式設計

 5)__tostring元方法

将表當作字元串使用(如print(table))時定義表對應的字元串。

mytable = {'lua','java','c#','c++'}

mymetatable = {
__tostring = function(tab)
    str = ''
    for k,v in pairs(tab) do
        str = str..k..' '..v..','
    end
    return str
end
}

mytable = setmetatable(mytable,mymetatable)

print(mytable)      
Lua程式設計

 3.協程

定義和啟動協程。

方式一:

--定義協同函數
co = coroutine.create(
    function (a,b)  --必須是匿名函數
        print(a+b)
    end
)

--運作協同函數
coroutine.resume(co,20,40)      
Lua程式設計

 方式二:

--定義協同函數
co = coroutine.wrap(
    function (a,b)  --必須是匿名函數
        print(a+b)
    end
)

--運作協同函數
co(20,40)      
Lua程式設計

 協程的挂起和繼續運作。

--定義協同函數
co = coroutine.create(
    function (a,b)
        print(a+b)
        coroutine.yield()  --挂起協同函數
        print(a-b)
    end
)

--運作協同函數
coroutine.resume(co,20,40)

--這句代碼的位置在運作協同函數的代碼後,在重新開機協同函數的代碼前,是以挂起協同函數後會運作這段代碼
print("I'm here")

--繼續運作協同函數
coroutine.resume(co)      
Lua程式設計

 協同程式的傳回值。

co = coroutine.create(
    function (a,b)
        return a+b,a-b
    end
)

--協同函數預設有一個boolean類型的傳回值表示是否啟動成功,自己定義的其他傳回值作為第二個、第三個......等傳回值
res1,res2,res3 = coroutine.resume(co,20,40)

print(res1,res2,res3)      
Lua程式設計
co = coroutine.create(
    function (a,b)
        print('........................')
        coroutine.yield(a+b,a-b)
        print('........................')
        return a*b,a/b
    end
)

--當協同函數中間被暫停時,可以分階段傳回不同的傳回值,使目前階段暫停的yield函數括号中的參數作為目前階段的傳回值
res1,res2,res3 = coroutine.resume(co,20,40)

print(res1,res2,res3)

--最後一個運作階段的傳回值為return傳回的内容
res4,res5,res6 = coroutine.resume(co)

print(res4,res5,res6)      
Lua程式設計

 協程的狀态(3種)。

co = coroutine.create(
    function (a,b)
        print(coroutine.status(co))  --running運作
        print('........................')
        coroutine.yield()
        print('........................')
        print(coroutine.status(co))  --running運作
    end
)

print(coroutine.status(co))  --suspended暫停
coroutine.resume(co,20,40)
print(coroutine.status(co))  --suspended暫停
coroutine.resume(co)
print(coroutine.status(co))  --dead死亡      
Lua程式設計

 擷取正在運作的協程。

co = coroutine.create(
    function (a,b)
        print(coroutine.running())  --擷取正在運作的協程
    end
)

coroutine.resume(co,20,40)      
Lua程式設計

 4.檔案I/O

檔案的簡單讀取和寫入。

f = io.open('iotest.txt','r')  --打開檔案
io.input(f)  --建立輸入流
print(io.read())  --read函數讀取一行
print(io.read())
print(io.read())
print(io.read())
io.close()  --關閉流      
Lua程式設計

 open函數的第一個參數是檔案的相對位址和名稱,第二個參數是可選參數,對應打開方式。打開方式有:r(隻讀,檔案必須存在)、w(隻寫,寫入的檔案原有資料會被清空,檔案不存在會自動建立檔案)、a(以附加的方式打開隻寫檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾,即檔案原先的内容會被保留)、r+(以可讀寫方式打開檔案,該檔案必須存在)、w+(打開可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案内容會消失。若檔案不存在則建立該檔案)、a+(與a類似,但此檔案可讀可寫)、b(二進制模式,如果檔案是二進制檔案,可以加上b)

f = io.open('iotest.txt','a')  --打開檔案,a為追加的形式隻寫,w為清空後隻寫
io.output(f)  --建立輸出流
print(io.write(''))  --write函數寫入内容,傳回值代表是否寫入成功
io.close()  --關閉流      
Lua程式設計

 read函數的參數。參數有:"*n"(讀取一個數字并傳回)、"*a"(從目前位置讀取整個檔案)、"*l"(預設參數,讀取下一行)、number(傳回指定個數的字元串)。

f = io.open('iotest.txt','r')
io.input(f)
print(io.read("*l"))  --讀取一行
print(io.read("*n"))  --讀取一個數字
print(io.read(10))  --讀取10個字元
print(io.read("*a"))  --讀取剩下的所有内容
io.close()      
Lua程式設計

 完全模式。完全模式下,可以同時處理多個檔案。

f = io.open('iotest.txt','r')

--使用f:read代替io.read
print(f:read())

file.close()      
Lua程式設計

 5.lua實作面向對象程式設計

lua中并沒有直接實作面向對象程式設計,但是可以使用表間接實作面向對象。

--定義一個人的對象
person = {name='movin',age=18}

person.eat = function ()
    print(person.name..'在吃飯')
end

person.eat()      
Lua程式設計

 優化面向對象的實作。

--定義一個人的對象
person = {name='movin',age=18}

--将對象自身作為變量傳遞,否則這裡對象的名稱不能修改
person.eat = function (self)
    print(self.name..'在吃飯')
end

person.eat(person)      
Lua程式設計
--定義一個人的對象
person = {name='movin',age=18}

--使用冒号定義和調用,不用傳遞self參數,其中self就指代調用者
function person:eat()
    print(self.name..'在吃飯')
end

person:eat()      
Lua程式設計

 根據模闆建立新對象。

Person = {name='movin',age=18}

function Person:eat()
    print(self.name..'在吃飯')
end

--建立新的對象的new方法
function Person:new()
    local t = {}
    --使用元表的__index元方法指向Person對象
    setmetatable(t,{__index=self})
    return t
end

person1 = Person:new()
person2 = Person:new()

print(person1.name)
person2:eat()

--修改對象中的屬性值相當于在對象中設定了新值,再查找這個索引對應的值時就不會在Person中查找,相當于實作了修改屬性和重寫方法的效果
person1.name = 'ww'

print(person1.name)      
Lua程式設計

繼續閱讀