lua库学习笔记
1.数学库
所有数学库都包含在math表对象中。
math.xxx(sin、cos、tan、asin...)直接调用即可。
math.random(int m, [int n])用于生存随机数
不提供参数返回0-1数字,提供m返回1到m随机整数,m,n则返回[m,n]
2.表库
插入 table.insert
1 t={1, 2,3} 2 /*插入指定位置*/ 3 table.insert(t, 2, 99) //t={1, 99, 2, 3} 4 /*插入表尾*/ 5 table.insert(t, 100) //t={1, 99, 2, 3, 100}
移除 table.remove
/*移除指定位置,后面元素自动前移*/ table.remove(t, 2) //t={1, 2, 3, 100} /*移除尾部元素*/ table.remove(t) //t={1, 2, 3}
连接 table.concat
1 /*将字符串 数组拼接返回*/ 2 table.concat({"hello ", "world"}) // hello world 3 /*出入分割符参数*/ 4 table.concat({"hello ", "world", ":"}) // hello :world 5 /*出入起始索引和结束索引*/ 6 table.concat({"1 ", "2", "3" ,"4"}, "-", 2, 3 ) // 2-3
排序 table.sort
1 /*传入表*/ 2 local t={"al", "bcd", "mga", "de"} 3 table.sort(t) 4 ->t={"al", "bcd", "de", "mqa"} 5 /*传入排序函数*/ 6 local sortFunc = function(a, b) return b < a end; 7 table.sort(t, sortFunc) 8 ->t={"mqa", "de", "bcd", "al"};
3.字符串库
基本函数
string.rep(s,n) 返回字符串重复n次的结果
string.len(s) 返回字符产长度
string.upper(s) 转为大写
string.lower(s) 转为小写
string.sub(s,i,j) 返回要的提取字符串
string.char和string.byte 字符数值和对应字符相互转换
string.format调用和c语言printf规则基本一致
模式匹配
string库的模式匹配没有用到正则表达式,功能会弱点,但在处理字符串方面还是很强大的
搜索特定模式 string.find
1 s = "hello world" 2 i, j = string.find(s, "hello") 3 print(i, j) --> 1 5 4 print(string.sub(s, i, j)) --> hello 5 6 print(string.find(s, "world")) --> 7 11 7 i, j = string.find(s, "l") 8 print(i, j) --> 3 3 9 print(string.find(s, "lll")) --> nil
4.I/O库
简单模型
io.input 设置当前输入文件
io.output 设置当前输出文件
io.write 输出
1 /*写入当前输出文件*/ 2 io.write("hello", " world") ->hello world
io.read 读取
/*读取整个输入文件*/ t = io.read("*a") /*读取文件下一行,不包括换行符*/ t = io.read("*l") /*读取文件下一行,包括换行符*/ t = io.read("*L") /*读取一个数字*/ t = io.read("*n") /*读取num个数字*/ t = io.read(num)
完整模型
/*打开文件*/ local f = io.open(filename,"r"); /*读取文件*/ local t= f:read("*a"); /*关闭文件*/ f:close();