–Lua中的数学库
–如果想使用数学库的函数,可以直接使用,不需要重新手动导入
–获取系统时间
–os.time在单机游戏中做每日任务,就可以通过这个对比 是否可以领取奖励
print(os.time())
--math.sin(x) x是弧度
--math.deg(x) 将角度转换为弧度
--math.rad(x) 将弧度转化为角度
--lua数学库的指数和对数
--math.exp(x)
--math.log(x)
–取整
local num1 = 2.3
print(math.floor(num1))--向下取整
print(math.ceil(num1)) --向下取整
--max min
--math.min(x,...)
--math.max(x,...)
–伪随机数
math.randomseed(os.time())
print(math.random())
print(math.random(3))
print(math.random(2,9))
print(math.random(1,30))
–table库中的常用函数
--1.插入删除
--table.insert(table,[pos,]value)
t = {
1,2,3,4,5
}
table.insert(t,1,10)
--table.insert(t,0,8)--error
for i,v in ipairs(t) do
print(i,v)
end
table.remove(t,5)
for i,v in ipairs(t) do
print(i,v)
end
--不指定位置的话 默认最后一个位置·
–排序 sort
--table.sort(tablename,sortfunction)
table.sort(t)--默认从小到大
for i,v in ipairs(t) do
print(i,v)
end
print (">>>>>>>>>>>>>>>>\n")
local function my_sort( x,y )
if x>y then
return true
end
return false
end
table.sort(t,my_sort)
for i,v in ipairs(t) do
print(i,v)
end
–连接函数
--table.concat(tablename,",",start_index,end_index)
print(">>>>>>>>>>>>>>>>>")
local string_contact = {"string","number","int","double"}
string_contact = table.concat(string_contact,",",2,4)
print(string_contact)
--删除的另一种方法
--指定tt[n] = nil 但是这种方法 所以不会变化 必须1,2,3 把第二个元素nil 则索引 为1 3
--容易出错 不建议使用
--比如用上边方法删除元素 三个元素中删除第二个 然后用#获得table的长度 变为1
–string 库
--find
local test_string = "today is a good day"
i,j = string.find(test_string,"day")
print(i,j)--i代表所找到的字符串的第一个元素的坐标 和该字符串结束的位置
--match
m = string.match(test_string,"today")
print(m)
--截字符串
s = string.sub(test_string,1,5)
t = string.sub(test_string,1,-1)
print(s)
print(t)
--gsub --找到 替换
--替换的是一个副本 并不改变原本的
n = string.gsub(test_string,"today","tomorrow")
print(n)
print(test_string)
–***********
--IO
local m = require("io")
m.write("sin(3) = ",math.sin(3),"\n")
m.write(string.format("sin(3) = %.4f\n",math.sin(3)))
print("12"..33)
io.write("12",33,"\n")
local f = assert(io.open("bb.txt",'r'))
local t = f:read("*all")
print(t)
f:close()--可以用来读取文件
function write_st( message )
local file = assert(io.open("a.txt",'a'))
file :write(message)
file:clos()
end
write_st("piehuoyo")
function write_other_st( mes )
local temp = io.input()
io.input("new.txt")
io.write(message)
end