Lua学习笔记(函数)
2016-01-26 09:23
621 查看
使用函数
创建函数
局部函数
函数的参数与返回值
函数作为Lua值
常用函数
print
type
tostring
tonumber
stringlen
function关键字用于创建新的函数,可以将其存放在一个变量中,或直接调用。
例:
运行结果:
函数从function()处开始,end关键字处结束。
语法糖:
将函数赋值给局部变量,即为局部函数。可以防止其它插件调用此函数。
语法糖:
当调用一个函数时,它可以接收任意多个参数供其使用。在它完成时,可以返回任意多个值。
将摄氏温度转化为华氏温度:
运行结果:
语法糖:
当有函数未传递参数时,默认值为nil,会报错。
函数的返回值不是必须的。
在Lua中,每个函数只是一个简单的Lua值,它的类型是function。这些值可以被比较(使用”==”和”~=”)、绑定到变量名、传递给函数、从函数中返回或作为table中的关键字。能以这样的方式对待的Lua值被称为头等对象,而支持这种方式的函数被成为头等函数。
运行结果:
运行结果:
运行结果:
例:
运行结果:
例:
运行结果:
运行结果:
运行结果:
运行结果:
运行结果:
创建函数
局部函数
函数的参数与返回值
函数作为Lua值
常用函数
type
tostring
tonumber
stringlen
使用函数 |
创建函数 |
例:
>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值 |
>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
相关文章推荐
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 文件遍历排序函数
- 详解Lua中的表的概念及其相关操作方法
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- Lua编程示例(二):面向对象、metatable对表进行扩展
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)
- DOS批处理 函数定义与用法
- asp Chr 函数 数字转字母的方法
- 把Lua编译进nginx步骤方法
- Lua脚本自动生成APK包
- Lua中的元表(metatable)、元方法(metamethod)详解
- Lua中的metatable介绍
- Lua中ipair和pair的区别
- Lua中的函数精讲笔记
- 浅谈Lua的面向对象特性
- 详解Lua中的变量相关知识点
- Lua脚本语言入门笔记