函數(shù)是一起執(zhí)行任務(wù)的一組語句,您可以將代碼分成單獨(dú)的函數(shù)。
Lua語言提供了程序可以調(diào)用的許多內(nèi)置方法。如方法 print()打印在控制臺(tái)中作為輸入傳遞的參數(shù)。
定義函數(shù)
Lua編程語言中方法定義的一般形式如下-
optional_function_scope function function_name( argument1, argument2, argument3........, argumentn) function_body return result_params_comma_separated end
Lua編程語言中的方法定義由方法標(biāo)頭和方法主體組成。這是方法的所有部分-
Optional_function? ? ?- 可選,默認(rèn)為global,您可以使用關(guān)鍵字 local 來定義為局部函數(shù)。
function? ? ? ? ? ? ? ? ? ? ? ? - 這是函數(shù)的實(shí)際名稱。
arguments? ? ? ? ? ? ? ? ? ? - 參數(shù)就像一個(gè)占位符,調(diào)用函數(shù)時(shí),將一個(gè)值傳遞給參數(shù),此值稱為實(shí)際參數(shù)或自變量。
function_body? ? ? ? ? ? ?- 方法主體包含用于定義方法函數(shù)的語句的集合。
return? ? ? ? ? ? ? ? ? ? ? ? ? ? - 在Lua中,可以通過在return關(guān)鍵字后面加上逗號(hào)分隔的返回值來返回多個(gè)值。
以下是名為 max()的函數(shù)的源代碼。此函數(shù)采用兩個(gè)參數(shù)num1和num2,并返回兩個(gè)參數(shù)之間的最大值-
--[[ function returning the max between two numbers --]] function max(num1, num2) if (num1 > num2) then result = num1; else result = num2; end return result; end
調(diào)用函數(shù)
在創(chuàng)建Lua函數(shù)時(shí),您需要定義函數(shù)的函數(shù)。要使用方法,您將必須調(diào)用該函數(shù)來執(zhí)行定義的任務(wù)。
要調(diào)用方法,您只需要傳遞所需的參數(shù)以及方法名稱,并且如果該方法返回一個(gè)值,則可以存儲(chǔ)返回的值。如-
function max(num1, num2) if (num1 > num2) then result = num1; else result = num2; end return result; end -- calling a function print("The maximum of the two numbers is ",max(10,4)) print("The maximum of the two numbers is ",max(5,6))
當(dāng)無涯教程運(yùn)行上面的代碼時(shí),將獲得以下輸出。
The maximum of the two numbers is 10 The maximum of the two numbers is 6
傳遞函數(shù)
在Lua中,可以將函數(shù)分配給變量,也可以將它們作為另一個(gè)函數(shù)的參數(shù)傳遞。這是在Lua中分配和傳遞函數(shù)作為參數(shù)的簡單示例。
myprint = function(param) print("This is my print function - ##",param,"##") end function add(num1,num2,functionPrint) result = num1 + num2 functionPrint(result) end myprint(10) add(2,5,myprint)
當(dāng)運(yùn)行上面的代碼時(shí),將獲得以下輸出。
This is my print function - ## 10 ## This is my print function - ## 7 ##
函數(shù)變量
可以使用...作為參數(shù)在Lua中使用可變參數(shù)創(chuàng)建函數(shù),在該示例中該函數(shù)將返回平均值并且接受可變參數(shù)。
function average(...) result = 0 local arg = {...} for i,v in ipairs(arg) do result = result + v end return result/#arg end print("The average is",average(10,5,3,4,5,6))
當(dāng)無涯教程運(yùn)行上面的代碼時(shí),將獲得以下輸出。文章來源:http://www.zghlxwxcb.cn/news/detail-622001.html
The average is 5.5
Lua - 函數(shù)聲明 - 無涯教程網(wǎng)無涯教程網(wǎng)提供函數(shù)是一起執(zhí)行任務(wù)的一組語句,您可以將代碼分成單獨(dú)的函數(shù)。Lua語言提供了程序可以...https://www.learnfk.com/lua/lua-functions.html文章來源地址http://www.zghlxwxcb.cn/news/detail-622001.html
到了這里,關(guān)于無涯教程-Lua - 函數(shù)聲明的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!