1. 程式人生 > >Lua學習筆記(函式)

Lua學習筆記(函式)

使用函式
建立函式

  function關鍵字用於建立新的函式,可以將其存放在一個變數中,或直接呼叫。
  例:

>hello = function()
>>print("Hello World!")
>>end
>hello()

  執行結果:Hello World!
  函式從function()處開始,end關鍵字處結束。
  語法糖:

>function hello()
>>print("Hello World!")
>>end
區域性函式

  將函式賦值給區域性變數,即為區域性函式。可以防止其它外掛呼叫此函式。

>local hello = function()
>>print("Hello World!")
>>end

  語法糖:

>local function hello()
>>print("Hello World!")
>>end
函式的引數與返回值

  當呼叫一個函式時,它可以接收任意多個引數供其使用。在它完成時,可以返回任意多個值。
  將攝氏溫度轉化為華氏溫度:

>convert_c2f = function(celsius)
>>local converted = (celsius * 1.8
) + 32 >>return converted >>end >print(convert_c2f(10))

  執行結果:50
  語法糖:

>function convert_c2f(celsius)
>>local converted = (celsius * 1.8) + 32
>>return converted
>>end

  當有函式未傳遞引數時,預設值為nil,會報錯。
  函式的返回值不是必須的。

函式作為Lua值

  在Lua中,每個函式只是一個簡單的Lua值,它的型別是function。這些值可以被比較(使用”==”和”~=”)、繫結到變數名、傳遞給函式、從函式中返回或作為table中的關鍵字。能以這樣的方式對待的Lua值被稱為頭等物件,而支援這種方式的函式被成為頭等函式。

>hello = function()
>>print("Hello World!")
>>end
>print(hello == hello)

  執行結果:true

>hello2 = hello
>print(hello2 == hello)

  執行結果:true

>hello2 = function()
>>print("Hello World!")
>>end
>print(hello2 == hello)

  執行結果:false

常用函式

print()

  說明:輸出
  例:

print("Hello World!")

  執行結果:Hello World!

type()

  說明:確定引數型別,返回值為字串。
  例:

print(type(5))

  執行結果:number

tostring()

  說明:將任意引數轉換為字串。

foo = tostring(11)
print(type(foo))

  執行結果:string

tonumber()

  說明:獲取一個值並把它轉換成一個數,如果不能轉換,返回nil。

foo = tonumber("123")
print(type(foo))

  執行結果:number

string.len()

  說明:獲取字串長度,相當於在字串前加#號。

print(string.len("Hello"))

  執行結果:5

print(#"Hello")

  執行結果:5