您的位置:首页 > 编程语言 > Lua

Lua学习笔记(函数)

2016-01-26 09:23 621 查看
使用函数
创建函数

局部函数

函数的参数与返回值

函数作为Lua值

常用函数

print

type

tostring

tonumber

stringlen

使用函数

创建函数

  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua 函数