1) math库
math.random(os.time()) 随机种子
os.time()表示当前时间,返回距离到现在的秒数,跟C++的time(NULL)一样。
math.random() --返回0-1之间的随机数
math.random(5) --返回1-5之间的整数(包括1和5)
math.random(5, 10) --返回5到10之间的整数(包括5和10)
math.floor(5.125) -- 5 向下取整函数
如果想对一个数四舍五入,那么可以让它加上0.5,再向下取整。
math.ceil(9.1) --10 向上取整
math.pi --3.1415926535898(圆周率)
math.abs(-2012) 2012(取绝对值)
math.max(2, 4, 6, 8) -- 8取最大值
math.min(2, 4, 6, 8) -- 2取最小值
math.rad(180) --3.14159 角度转弧度
math.deg(math.pi) --180 弧度转角度
关于math库的更多用法,参见http://blog.youkuaiyun.com/goodai007/article/details/8076141
2) string库
数字和字符串相互转化 tonumber(“123”) tostring(123)
string.char(arg) --将整数转化为字符(根据ASCII编码)
string.byte(arg[,int]) --将字符转化为整数(可以指定某个字符,默认为第一个字符)
例如:string.char(97, 98, 99, 100) --abcd
string.byte(“abcd”, 4) --将第四个字符转化为其ASCII 68
string.byte(“abcd”) --默认将第一个字符转化为其ASCII 65
string.len(“abcd”) -- 4 求字符串的长度 等价于#“abcd”
string.upper(“abCD”) -- ABCD 将字符串转为大写
string.lower(“abCD”) -- abcd 将字符串转为小写
string.format(“%s”, “abc”) -- 格式化字符串
string.sub(“hello world”, 1, 5) -- hello 返回指定位置的字符(开始位置和结束位置)
string.gsub(“hello world”, “o”, “a”) -- hella warld
替换字符串(可以有第四个参数,表示替换次数,默认不写为全部替换)
a, b = string.find(“abcdefg”, “de”) -- 4, 5
返回指定字符串的开始下标和结束下标
string.reverse(“abcd”) -- “dcba” 将字符串反转
string.rep(“abcd”, 3) -- “abcdabcdabcd” 实现字符串的n个拷贝
看一个替换的例子:
myString = “happy, hello, home, hot, hudson”
myString = string.gsub(myString, “h%a+”, “An h word!”, 2)
print(myString) -- An h word!, An hword!, home, hot hudson
其中“h%a+”表示第一个字符是h,%a+表示任意长度的字母,并且在遇到空格或者标点符号时为止。
3) table库
table.getn(myTable) 返回表的长度(元素个数)
table.sort(myTable, func) 对表进行排序,按照函数来决定是升序还是降序
例如:
sortFunc = function(a, b) return a> b end
table.sort({“banana”, “orange”, “apple”, “grapes”}, sortFunc)
输出结果为:orange grapes, banana, apple
table.insert(myTable, [pos,] value)
在指定的位置插入元素(value),如果不指定位置,那么默认插入到表的末尾
table.remove(table[,pos])
删除并返回
table.concat(table[, “,”[, first[, end]]])
连接表
例如:fruits = {“banana”, “orange”, “apple”}
print(table.concat(fruits)) --bananaorangeapple
print(table.concat(fruits, “,”)) --banana,orange,apple
print(table.concat(fruits, “,”, 2, 3) --orange,apple
关于自己想查找任何库中的函数,可采用下面的方法进行输出判断:
for k, v in pairs(库) do
print(k)
end
比如:
for k, v in pairs(table) do
print(k)
end
--[[
sort
unpack
remove
insert
move
pack
concat
]]