Lua函数
Lua 函数
函数用于将一组语句组合起来完成一个任务。你可以将你的代码分割到不同的函数中。如何将你的代码分到不同的函数中完全由你自己决定,不过一般会按照逻辑功能进行划分,每个函数都执行一个特定的任务。
在 Lua 中提供了大量的内置函数供我们使用。例如,print() 函数用于将输入的参数输出到终端。
函数往往也被称作方法,子例程或过程等等。
函数定义
Lua 中函数定义的语法如下所示:
1 | optional_function_scope function function_name( argument1, argument2, argument3..., argumentn) |
–[[ function returning the max between two numbers –]]
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
1 |
|
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
– 调用函数
print(“The maximum of the two numbers is “,max(10,4))
print(“The maximum of the two numbers is “,max(5,6))
1 |
|
The maximum of the two numbers is 10
The maximum of the two numbers is 6
1 |
|
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)
1 |
|
This is my print function - ## 10 ##
This is my print function - ## 7 ##
1 |
|
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))
1 |
|
The average is 5.5
```