161218 Lua学习笔记-代码+笔记《库函数》

本文介绍了Lua编程语言中的数学库函数使用方法,包括取整、随机数生成等;演示了table库的操作,如插入、删除、排序及连接;并展示了string库的find、match等函数的应用。同时涉及了文件读写的IO操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

–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  但是这种方法 所以不会变化  必须123  把第二个元素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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值