【转】Lua math库


一、math库

atan2、sinh、cosh、tanh这4个应该用不到。

函数名 描述 示例 结果
pi 圆周率 math.pi 3.1415926535898
abs 取绝对值 math.abs(-2012) 2012
ceil 向上取整 math.ceil(9.1) 10
floor 向下取整 math.floor(9.9) 9
max 取参数最大值 math.max(2,4,6,8) 8
min 取参数最小值 math.min(2,4,6,8) 2
pow 计算x的y次幂 math.pow(2,16) 65536
sqrt 开平方 math.sqrt(65536) 256
mod 取模 math.mod(65535,2) 1
modf 取整数和小数部分 math.modf(20.12) 20   0.12
randomseed 设随机数种子 math.randomseed(os.time())  
random 取随机数 math.random(5,90) 5~90
rad 角度转弧度 math.rad(180) 3.1415926535898
deg 弧度转角度 math.deg(math.pi) 180
exp e的x次方 math.exp(4) 54.598150033144
log 计算x的自然对数 math.log(54.598150033144) 4
log10 计算10为底,x的对数 math.log10(1000) 3
frexp 将参数拆成x * (2 ^ y)的形式 math.frexp(160) 0.625    8
ldexp 计算x * (2 ^ y) math.ldexp(0.625,8) 160
sin 正弦 math.sin(math.rad(30)) 0.5
cos 余弦 math.cos(math.rad(60)) 0.5
tan 正切 math.tan(math.rad(45)) 1
asin 反正弦 math.deg(math.asin(0.5)) 30
acos 反余弦 math.deg(math.acos(0.5)) 60
atan 反正切 math.deg(math.atan(1)) 45

点击查看原文


二、table库

一部分的table函数只对其数组部分产生影响, 而另一部分则对整个table均产生影响. 下面会分开说明. 


> table.concat(table, sep,  start, end)


concat是concatenate(连锁,连接)的缩写。 table.concat()函数列出参数中指定table的数组部分从start位置到end位置的所有元素,元素间以指定的分隔符(sep)隔开。除了table外, 其他的参数都不是必须的,分隔符的默认值是空字符, start的默认值是1, end的默认值是数组部分的总长。


sep, start, end这三个参数是顺序读入的,所以虽然它们都不是必须参数,但如果要指定靠后的参数,必须同时指定前面的参数。

> tbl = {"alpha", "beta", "gamma"}
> print(table.concat(tbl, ":"))
alpha:beta:gamma
> print(table.concat(tbl, nil, 1, 2))
alphabeta
> print(table.concat(tbl, "\n", 2, 3))
beta
gamma


> table.insert(table, pos, value)


table.insert()函数在table的数组部分指定位置(pos)插入值为value的一个元素, pos参数可选, 默认为数组部分末尾。

> tbl = {"alpha", "beta", "gamma"}
> table.insert(tbl, "delta")
> table.insert(tbl, "epsilon")
> print(table.concat(tbl, ", ")
alpha, beta, gamma, delta, epsilon
> table.insert(tbl, 3, "zeta")
> print(table.concat(tbl, ", ")
alpha, beta, zeta, gamma, delta, epsilon


> table.maxn(table)


table.maxn()函数返回指定table中所有正数key值中最大的key值. 如果不存在key值为正数的元素, 则返回0. 此函数不限于table的数组部分.

> tbl = {[1] = "a", [2] = "b", [3] = "c", [26] = "z"}
> print(#tbl)
3               -- 因为26和之前的数字不连续, 所以不算在数组部分内
> print(table.maxn(tbl))
26
> tbl[91.32] = true
> print(table.maxn(tbl))
91.32


> table.remove(table, pos)


table.remove()函数删除并返回table数组部分位于pos位置的元素. 其后的元素会被前移. pos参数可选, 默认为table长度, 即从最后一个元素删起。


> table.sort(table, comp)


table.sort()函数对给定的table进行升序排序.

> tbl = {"alpha", "beta", "gamma", "delta"}
> table.sort(tbl)
> print(table.concat(tbl, ", "))
alpha, beta, delta, gamma


comp是一个可选的参数, 此参数是一个外部函数, 可以用来自定义sort函数的排序标准.

此函数应满足以下条件: 接受两个参数(依次为a, b), 并返回一个布尔型的值, 当a应该排在b前面时, 返回true, 反之返回false。


例如, 当我们需要降序排序时, 可以这样写:

> sortFunc = function(a, b) return b < a end
> table.sort(tbl, sortFunc)
> print(table.concat(tbl, ", "))
gamma, delta, beta, alpha


用类似的原理还可以写出更加复杂的排序函数. 例如, 有一个table存有工会三名成员的姓名及等级信息:

guild = {}

table.insert(guild, {
 name = "Cladhaire",
 class = "Rogue",
 level = 70,
})

table.insert(guild, {
 name = "Sagart",
 class = "Priest",
 level = 70,
})

table.insert(guild, {
 name = "Mallaithe",
 class = "Warlock",
 level = 40,
})


对这个table进行排序时, 应用以下的规则: 按等级升序排序, 在等级相同时, 按姓名升序排序。

可以写出这样的排序函数:

function sortLevelNameAsc(a, b)
 if a.level == b.level then
  return a.name < b.name
 else
  return a.level < b.level
 end
end

测试功能如下:

> table.sort(guild, sortLevelNameAsc)
> for idx, value in ipairs(guild) do print(idx, value.name) end
1, Mallaithe
2, Cladhaire
3, Sagart


> table.foreachi(table, function(i, v))


会期望一个从 1(数字 1)开始的连续整数范围,遍历table中的key和value逐对进行function(i, v)操作,适用于table是数组的情况。

t1 = {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="hello lua"};
table.foreachi(t1, function(i, v) print (i, v) end) ; --等价于foreachi(t1, print)

输出结果:
1 2
2 4
3 6
4 8
5 10
6 12


> table.foreach(table, function(i, v))


与foreachi不同的是,foreach会对整个表进行迭代

t1 = {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="hello lua"}
table.foreach(t1, function(i, v) print (i, v) end)

输出结果:
1 2
2 4
3 6
4 8
5 10
6 12
web hello lua
language Lua
version 5

> table.getn(table)


返回table中元素的个数,只适合table是数组的情况

t1 = {1, 2, 3, 5};
print(getn(t1))
->4

> table.setn(table, nSize)


设置table中的元素个数


三、string库

You can find details about the string library in section 5.4 of the Reference Manual [1]. For practical examples of usage of the string library, have a look at StringRecipes.

Note: In Lua string indices start at index value 1, not index value 0 (as they do in C).

string.byte(s [, i [, j]])

s:byte([, i [, j]])

Return the numerical code the i-th through j-th character of the string passed.

> = string.byte("ABCDE")      -- no index, so the first character
65
> = string.byte("ABCDE",1)    -- indexes start at 1
65
> = string.byte("ABCDE",0)    -- we're not using C
> = string.byte("ABCDE",100)  -- index out of range, no value returned
> = string.byte("ABCDE",3,4)
67      68
> s = "ABCDE"
> = s:byte(3,4)               -- can apply directly to string variable
67      68

string.char(i1, i2, ...)

Generate a string representing the character codes passed as arguments. Numerical codes are not necessarily portable across platforms.

> = string.char(65,66,67)
ABC
> = string.char()  -- empty string

string.dump(function)

Returns a binary representation of the given function, so that a later loadstring on that string returns a copy of the function. Function must be a Lua function without upvalues.

string.find(s, pattern [, init [, plain]])

s:find(pattern [, init [, plain]])

Find the first occurance of the pattern in the string passed. If an instance of the pattern is found a pair of values representing the start and end of the string is returned. If the pattern cannot be found nilis returned.

> = string.find("Hello Lua user", "Lua")
7       9
> = string.find("Hello Lua user", "banana")
nil

We can optionally specify where to start the search with a third argument. The argument may also be negative which means we count back from the end of the string and start the search.

> = string.find("Hello Lua user", "Lua", 1)  -- start at first character
7       9
> = string.find("Hello Lua user", "Lua", 8)  -- "Lua" not found again after character 8
nil
> = string.find("Hello Lua user", "e", -5)   -- first "e" 5 characters from the end
13      13

The pattern argument also allows more complex searches. See the PatternsTutorial for more information. We can turn off the regular expression feature by using the optional fourth argument plainplain takes a boolean value and must be preceeded by init. E.g.,

> = string.find("Hello Lua user", "%su")          -- find a space character followed by "u"
10      11
> = string.find("Hello Lua user", "%su", 1, true) -- turn on plain searches, now not found
nil

string.format(formatstring, e1, e2, ...)

formatstring:format(e1, e2, ...)

Create a formatted string from the format and arguments provided. This is similar to the printf("format",...) function in C. An additional option %qputs quotes around a string argument's value.

  • c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument.
  • q and s expect a string.
> = string.format("%s %q", "Hello", "Lua user!")   -- string and quoted string
Hello "Lua user!"
> = string.format("%c%c%c", 76,117,97)             -- char
Lua
> = string.format("%e, %E", math.pi,math.pi)       -- exponent
3.141593e+000, 3.141593E+000
> = string.format("%f, %g", math.pi,math.pi)       -- float and compact float
3.141593, 3.14159
> = string.format("%d, %i, %u", -100,-100,-100)    -- signed, signed, unsigned integer
-100, -100, 4294967196
> = string.format("%o, %x, %X", -100,-100,-100)    -- octal, hex, hex
37777777634, ffffff9c, FFFFFF9C

string.gmatch(s, pat)

s:gmatch(pat)

This returns a pattern finding iterator. The iterator will search through the string passed looking for instances of the pattern you passed.

> for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
Hello
Lua
user

For more information on iterators read the ForTutorial and IteratorsTutorial. For more information on patterns read the PatternsTutorial.

string.gsub(s, pattern, replace [, n])

s:gsub(pattern, replace [,n])

This is a very powerful function and can be used in multiple ways. Used simply it can replace all instances of the pattern provided with the replacement. A pair of values is returned, the modified string and the number of substitutions made. The optional fourth argument ncan be used to limit the number of substitutions made:

> = string.gsub("Hello banana", "banana", "Lua user")
Hello Lua user  1
> = string.gsub("banana", "a", "A", 2)  -- limit substitutions made to 2
bAnAna  2

Just like string.find() we can use regular expressions to search in strings. Patterns are covered in the PatternsTutorial. If a capture is used this can be referenced in the replacement string using the notation %capture_index, e.g.,

> = string.gsub("banana", "(an)", "%1-")    -- capture any occurances of "an" and replace
ban-an-a        2
> = string.gsub("banana", "a(n)", "a(%1)")  -- brackets around n's which follow a's
ba(n)a(n)a      2
> = string.gsub("banana", "(a)(n)", "%2%1") -- reverse any "an"s
bnanaa  2

If the replacement is a function, not a string, the arguments passed to the function are any captures that are made. If the function returns a string, the value returned is substituted back into the string.

> = string.gsub("Hello Lua user", "(%w+)", print)  -- print any words found
Hello
Lua
user
        3
> = string.gsub("Hello Lua user", "(%w+)", function(w) return string.len(w) end) -- replace with lengths
5 3 4   3
> = string.gsub("banana", "(a)", string.upper)     -- make all "a"s found uppercase
bAnAnA  3
> = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
bnanaa  2

Pattern capture, the most commonly seen pattern capture could be (.-), example "{(.-)}" means capture any characters between the braces {}. Another pattern seen sometimes is (.*) which means captures everything including braces found, two examples here illustrate the difference.

> = string.gsub("The big {brown} fox jumped {over} the lazy {dog}.","{(.-)}", function(a)  print(a) end )
brown 
over 
dog

> = string.gsub("The big {brown} fox jumped {over} the lazy {dog}.","{(.*)}", function(a)  print(a) end )
brown} fox jumped {over} the lazy {dog

string.len(s)

s:len()

Return the length of the string passed.

> = string.len("Lua")
3
> = string.len("")
0
> = string.len("Lua\000user")   -- Lua strings are 8 bit pure so \000 does not terminate
8

string.lower(s)

s:lower()

Make uppercase characters lower case.

> = string.lower("Hello, Lua user!")
hello, lua user!

string.match (s, pattern [, init])

s:match(pattern [, init])

Extract substrings by matching patterns.

> = string.match("I have 2 questions for you.", "%d+ %a+")
2 questions

> = string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"))
2, "questions"

string.rep(s, n)

s:rep(n)

Generate a string which is n copies of the string passed concatenated together.

> = string.rep("Lua ",5)
Lua Lua Lua Lua Lua
> = string.rep("Lua\n",3)
Lua
Lua
Lua

string.reverse(s)

s:reverse()

Reverses a string.

> = string.reverse("lua")
aul

string.sub(s, i [, j])

s:sub(i [,j])

Return a substring of the string passed. The substring starts at i. If the third argument j is not given, the substring will end at the end of the string. If the third argument is given, the substring ends at and includes j.

> = string.sub("Hello Lua user", 7)      -- from character 7 until the end
Lua user
> = string.sub("Hello Lua user", 7, 9)   -- from character 7 until and including 9
Lua
> = string.sub("Hello Lua user", -8)     -- 8 from the end until the end
Lua user
> = string.sub("Hello Lua user", -8, 9)  -- 8 from the end until 9 from the start
Lua
> = string.sub("Hello Lua user", -8, -6) -- 8 from the end until 6 from the end
Lua

string.upper(s)

s:upper()

Make all the lower case characters upper case.

> = string.upper("Hello, Lua user!")
HELLO, LUA USER!
没有能处理汉字的。。。


基本函数

函数描述示例结果
len计算字符串长度string.len(“abcd”)4
rep返回字符串s的n个拷贝string.rep(“abcd”,2)abcdabcd
lower返回字符串全部字母大写string.lower(“AbcD”)abcd
upper返回字符串全部字母小写string.upper(“AbcD”)ABCD
format返回一个类似printf的格式化字符串string.format(“the value is:%d”,4)the value is:4
subreturns substring from index i to j of sstring.sub(“abcd”,2)bcd
string.sub(“abcd”,-2)cd
string.sub(“abcd”,2,-2)bc
string.sub(“abcd”,2,3)bc
find在字符串中查找string.find(“cdcdcdcd”,”ab”)nil
string.find(“cdcdcdcd”,”cd”)   2
string.find(“cdcdcdcd”,”cd”,7)   8
gsub在字符串中替换string.gsub(“abcdabcd”,”a”,”z”);zbcdzbcd    2
string.gsub(“aaaa”,”a”,”z”,3);zzza    3
byte返回字符的整数形式string.byte(“ABCD”,4)68
char
match
gmatch
将整型数字转成字符并连接
匹配出单条结果
匹配出多条结果
string.char(97,98,99,100)
string.match("a=svv12","=(%w+)")
string.gmatch( html1,"<img src='(.-)' />" );
abcd
svv12
匹配出所有img地址


基本模式串

字符类描述示例结果
.任意字符string.find(“”,”.”)nil
%s空白符string.find(“ab  cd”,”%s%s”)   4
%S非空白符string.find(“ab  cd”,”%S%S”)   2
%p标点字符string.find(“ab,.cd”,”%p%p”)   4
%P非标点字符string.find(“ab,.cd”,”%P%P”)   2
%c控制字符string.find(“abcd\t\n”,”%c%c”)   6
%C非控制字符string.find(“\t\nabcd”,”%C%C”)   4
%d数字string.find(“abcd12″,”%d%d”)   6
%D非数字string.find(“12abcd”,”%D%D”)   4
%x十六进制数字string.find(“efgh”,”%x%x”)   2
%X非十六进制数字string.find(“efgh”,”%X%X”)   4
%a字母string.find(“AB12″,”%a%a”)   2
%A非字母string.find(“AB12″,”%A%A”)   4
%l小写字母string.find(“ABab”,”%l%l”)   4
%L大写字母string.find(“ABab”,”%L%L”)   2
%u大写字母string.find(“ABab”,”%u%u”)   2
%U非大写字母string.find(“ABab”,”%U%U”)   4
%w字母和数字string.find(“a1()”,”%w%w”)   2
%W非字母非数字string.find(“a1()”,”%W%W”)   4

转义字符%

字符类描述示例结果
%转义字符string.find(“abc%..”,”%%”)   4
string.find(“abc..d”,”%.%.”)   5

用[]创建字符集,”-”为连字符,”^”表示字符集的补集

字符类描述示例结果
[01]匹配二进制数string.find(“32123″,”[01]“)   3
[AB][CD]匹配AC、AD、BC、BDstring.find(“ABCDEF”,”[AB][CD]“)   3
[[]]匹配一对方括号[]string.find(“ABC[]D”,”[[]]”)   5
[1-3]匹配数字1-3string.find(“312″,”[1-3][1-3][1-3]“)   3
[b-d]匹配字母b-dstring.find(“dbc”,”[b-d][b-d][b-d]“)   3
[^%s]匹配任意非空字符string.find(“  a  ”,”[^%s]“)   3
[^%d]匹配任意非数字字符string.find(“123a”,”[^%d]“)   4
[^%a]匹配任意非字母字符string.find(“abc1″,”[^%a]“)   4

用”()”进行捕获

字符类描述示例结果
()捕获字符串string.find(“12ab”,”(%a%a)”)   4    ab
string.find(“ab12″,”(%d%d)”)   4    12

模式修饰符

修饰符描述示例结果
+表示1个或多个,匹配最多个string.find(“aaabbb”,”(a+b)”)   4    aaab
string.find(“cccbbb”,”(a+b)”)nil
-表示0个或多个,匹配最少个string.find(“zzxyyy”,”(xy-)”)   3    x
string.find(“zzzyyy”,”(x-y)”)   4    y
*表示0个或多个,匹配最多个string.find(“mmmnnn”,”(m*n)”)   4    mmmb
string.find(“lllnnn”,”(m*n)”)   4    n
?表示0个或1个string.find(“aaabbb”,”(a?b)”)   4    ab
string.find(“cccbbb”,”(a?b)”)   4    b

四、io库

1io表调用方式:使用io表,io.open将返回指定文件的描述,并且所有的操作将围绕这个文件描述

  io表同样提供三种预定义的文件描述io.stdin,io.stdout,io.stderr

  2、文件句柄直接调用方式,即使用file:XXX()函数方式进行操作,其中fileio.open()返回的文件句柄

  多数I/O函数调用失败时返回nil加错误信息,有些函数成功时返回nil

  1io.close ([file])

  功能:相当于file:close(),关闭默认的输出文件

  2io.flush ()

  功能:相当于file:flush(),输出所有缓冲中的内容到默认输出文件

  3io.lines ([filename])

  功能:打开指定的文件filename为读模式并返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,并自动关闭文件

  若不带参数时io.lines() <=> io.input():lines(); 读取默认输入设备的内容,但结束时不关闭文件

  如:for line in io.lines("main.lua") do

  print(line)

  end

  4io.open (filename [, mode])

  功能:按指定的模式打开一个文件,成功则返回文件句柄,失败则返回nil+错误信息

  mode:

  "r": 读模式 (默认);

  "w": 写模式;

  "a": 添加模式;

  "r+": 更新模式,所有之前的数据将被保存

  "w+": 更新模式,所有之前的数据将被清除

  "a+": 添加更新模式,所有之前的数据将被保存,只允许在文件尾进行添加

  "b": 某些系统支持二进制方式

  5io.output ([file])

  功能:相当于io.input,但操作在默认输出文件上

  6io.popen ([prog [, mode]])

  功能:开始程序prog于额外的进程,并返回用于prog的文件句柄(并不支持所有的系统平台)

  7io.read (...)

  功能:相当于io.input():read

  8io.tmpfile ()

  功能:返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除

  9io.type (obj)

  功能:检测obj是否一个可用的文件句柄

  返回:

  "file":为一个打开的文件句柄

  "closed file":为一个已关闭的文件句柄

  nil:表示obj不是一个文件句柄

  10io.write (...)

  功能:相当于io.output():write

  11file:close()

  功能:关闭文件

  注:当文件句柄被垃圾收集后,文件将自动关闭。句柄将变为一个不可预知的值

  12file:flush()

  功能:向文件写入缓冲中的所有数据

  13file:lines()

  功能:返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,但不关闭文件

  如:for line in file:lines() do body end

  14file:read(...)

  功能:按指定的格式读取一个文件,按每个格式函数将返回一个字串或数字,如果不能正确读取将返回nil,若没有指定格式将指默认按行方式进行读取

  格式:

  "*n": 读取一个数字

  "*a": 从当前位置读取整个文件,若为文件尾,则返回空字串

  "*l": [默认]读取下一行的内容,若为文件尾,则返回nil

  number: 读取指定字节数的字符,若为文件尾,则返回nil;如果number0则返回空字串,若为文件尾,则返回nil;

  15file:seek([whence][,offset])

  功能:设置和获取当前文件位置,成功则返回最终的文件位置(按字节),失败则返回nil加错误信息

  参数

  whence:

  "set": 从文件头开始

  "cur": 从当前位置开始[默认]

  "end": 从文件尾开始

  offset:默认为0

  不带参数file:seek()则返回当前位置,file:seek("set")则定位到文件头,file:seek("end")则定位到文件尾并返回文件大小

  16file:setvbuf(mode,[,size])

  功能:设置输出文件的缓冲模式

  参数

  mode:

  "no": 没有缓冲,即直接输出

  "full": 全缓冲,即当缓冲满后才进行输出操作(也可调用flush马上输出)

  "line": 以行为单位,进行输出(多用于终端设备)

  最后两种模式,size可以指定缓冲的大小(按字节),忽略size将自动调整为最佳的大小

  17file:write(...)


五、os库

os.clock ()
功能:返回一个程序使用CPU时间的一个近似值

例如:
local x = os.clock();
print(os.clock())
local s = 0;
for i = 1, 100000000 do
      s = s + i;
end
print(string.format("elapsed time : %.2f\n", os.clock() - x));

输出:
0
elapsed time : 2.55


--------------------------------------------------------------------------------

os.date ([format [, time]])
功能:返回一个按format格式化日期、时间的字串或表
若设置time参数,则按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")
  
例如:
t = os.date("*t", os.time());
for i, v in pairs(t) do
      print(i, v);
end

输出:
hour  14
min   58
wday  2
day   10
month  8
year  2009
sec   18
yday  222
isdst  false

对于其它的格式字符串,os.date会将日期格式化为一个字符串

例如:
print(os.date("today is %A, in %B"))      -->today is Tuesday, in May
print(os.date("%x", 906000490))           -->09/16/1998

所有格式化字符串如下:
  
%a      一星期中天数的简写                      (Wed)
%A      一星期中天数的全称                      (Wednesday)
%b      月份的简写                                  (Sep)
%B      月份的全称                                  (September)
%c      日期和时间                                   (09/16/98 23:48:10)
%d      一个月中的第几天                          (16)[0 ~ 31]
%H      24小时制中的小时数                      (23)[00 ~ 23]
%I      12小时制中的小时数                       (11)[01 ~ 12]
%j      一年中的第几天                             (259)[01 ~ 366]
%M      分钟数                                       (48)[00 ~ 59]
%m      月份数                                       (09)[01 ~ 12]     
%P      "上午(am)" 或 "下午(pm)"               (pm)
%S      秒数                                          (10)[00 ~ 59]
%w      一星期中的第几天                         (3)[0 ~ 6 = 星期天 ~ 星期六]

 %W  一年中的第几个星期        0 ~ 52
%x      日期                                          (09/16/98)
%X      时间                                          (23:48:10)
%y      两位数的年份                               (90)[00 ~ 99]
%Y      完整的年份                                 (2009)
%%      字符串'%'


--------------------------------------------------------------------------------

os.difftime (t2, t1)
功能:返回t1到t2相差的秒数

例如:
t1 = os.time();
for i = 0, 10000000 do
 os.time();
end
t2 = os.time();
print(os.difftime(t2, t1));

输出:
2

--------------------------------------------------------------------------------

os.execute ([command])
功能:相当于C的system函数,返回系统状态码

例如:
os.execute("pause")

输出:
按任意键继续. . .

--------------------------------------------------------------------------------

os.exit ([code])
功能:相当于C的exit函数,终止主程序,code为返回值

例如:
os.exit(1)

--------------------------------------------------------------------------------

os.getenv (varname)-
功能:返回当前进程的环境变量varname的值,若变量没有定义时返回nil

例如:
print(os.getenv("USERDOMAIN"))
print(os.getenv("SystemRoot"))
print(os.getenv("Os2LibPath"))
print(os.getenv("ProgramFiles" ))
print(os.getenv("APPDATA" ))
print(os.getenv("ALLUSERSPROFILE" ))
print(os.getenv("CommonProgramFiles" ))
print(os.getenv("COMPUTERNAME" ))
print(os.getenv("USERNAME"))
print(os.getenv("USERPROFILE" ))
print(os.getenv("ComSpec"))
print(os.getenv("LOGONSERVER" ))
print(os.getenv("NUMBER_OF_PROCESSORS" ))
print(os.getenv("OS"))
print(os.getenv("PATHEXT" ))
print(os.getenv("PROCESSOR_ARCHITECTURE" ))
print(os.getenv("PROCESSOR_IDENTIFIER" ))
print(os.getenv("PROCESSOR_LEVEL" ))
print(os.getenv("PROCESSOR_REVISION" ))
print(os.getenv("USERDOMAIN"))
print(os.getenv("SystemRoot" ))
print(os.getenv("TEMP"))

输出:
RDEV
C:\WINDOWS
nil
C:\Program Files
C:\Documents and Settings\baiyun\Application Data
C:\Documents and Settings\All Users
C:\Program Files\Common Files
BAIYUN
baiyun
C:\Documents and Settings\baiyun
C:\WINDOWS\system32\cmd.exe
http://www.cnblogs.com/whiteyun/admin/file://rdev1/
2
Windows_NT
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.wlua
x86
x86 Family 15 Model 6 Stepping 5, GenuineIntel
15
0605
RDEV
C:\WINDOWS
C:\DOCUME~1\baiyun\LOCALS~1\Temp


--------------------------------------------------------------------------------

os.remove (filename)
功能:删除文件或一个空目录,若函数调用失败则返加nil加错误信息


--------------------------------------------------------------------------------

os.rename (oldname, newname)
功能:更改一个文件或目录名,若函数调用失败则返加nil加错误信息


--------------------------------------------------------------------------------

os.setlocale (locale [, category])
功能:设置程序的当前设置,函数返回最新的值,失败则返回nil
参数:
  locale:一个指定当前设置的字串
      "":一个空字串,当前设置被视为本地设置
     "c":当前设置被视为标准c设置
      nil:返回category指示设置名的当前值
  category:一个描述要更改的设置名 
         "all"[默认], "collate", "ctype", "monetary", "numeric", "time"


--------------------------------------------------------------------------------

os.time ([table])
功能:按table的内容返回一个时间值(数字),若不带参数则返回当前时间
table的字段:
  year, month, day, hour, min, sec, isdst

例如:
print(os.time());
-->1249887340
print(os.time({year=1970, month=1, day=1, hour=0}));
-->10500


--------------------------------------------------------------------------------

os.tmpname()
功能:返回一个临时文件名


六、debug库




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值