Lua中的常用操作系统库
最后更新于:2022-04-01 10:07:16
## os.time ([table])
功能:按table的内容返回一个时间值(数字),若不带参数则返回当前时间.(在许多系统中该数值是当前距离某个特定时间的秒数。)
说明:当为函数调用附加一个特殊的时间表时,该函数就是返回距该表描述的时间的数值。这样的时间表有如下的区间:

前三项是必需的,如果未定义后几项,默认时间为正午(12:00:00)。如果是在里约热内卢(格林威治向西三个时区)的一台Unix计算机上(相对时间为1970年1月1日,00:00:00),对于pc机(中国时区而言)有稍微更改,更改了为1970年1月1日,08:00:00,这是因我国与其它国家时间差导致。
例子:
~~~
print(os.time{year=1970, month=1, day=1,hour=8})
print(os.time{year=1970, month=1, day=1}) --若未定义“时,分,秒”,默认时间为正午(04:00:00)
~~~
运行结果:
-->0
-->14400(14400 = 4*60*60 )
## os.date ([format [, time]])
功能:返回一个按format格式化日期、时间的字串或表
说明:函数date,其实是time函数的一种“反函数”。它将一个表示日期和时间的数值,转换成更高级的表现形式。其第一个参数是一个格式化字符串,描述了要返回的时间形式。第二个参数就是时间的数字表示,默认为当前的时间。
参数:format:
*t":将返一个带year(4位),month(1-12), day (1--31), hour (0-23), min (0-59), sec (0-61), wday (星期几, 星期天为1), yday (年内天数), and isdst (是否为日光节约时间true/false)的带键名的表;
若没有"*t"则返回一个按C的strftime函数格式化的字符串;
若不带参数,则按当前系统的设置返回格式化的字符串 os.date() <=> os.date("%c")
例子:我当前PC时间,如图:

代码:
~~~
t = os.date("*t", os.time());
for i, v in pairs(t) do
print(i,"->",v);
end
~~~
运行结果 :

运行结果和以上时钟的秒,不一致,你想,截图也要时间的,呵呵。
如果使用带标记(见下表)的特殊字符串,os.data函数会将相应的标记位以时间信息进行填充,得到一个包含时间的字符串。

例子:
~~~
print(os.date("today is %A, in %B"))
print(os.date("%X", 906000490))
~~~
运行结果:

同时,也可以使用明确的字符串格式方式(例如"%m/%d/%Y")
例子:
~~~
print(os.date("%m/%d/%Y", 906000490))
~~~
运行结果:

## os.difftime (t2, t1)
功能:返回t1到t2相差的秒数
例子:
~~~
t1 = os.time();
for i = 0, 100000 do
os.time();
end
t2 = os.time();
print(string.format("t1: %d t2: %d",t1,t2))
print(os.date("%x", t1))
print(os.date("%X", t2))
print(os.difftime(t2, t1));
~~~
运行结果:

## os.clock ()
功能:返回一个程序使用CPU时间的一个近似值
例子:
~~~
local x = os.clock();
print(os.clock())
local s = 0;
for i = 1, 100000 do
s = s + i;
end
print(string.format("elapsed time : %.2f\n", os.clock() - x));
~~~
运行结果:
