【轉】Lua math庫
函式名 | 描述 | 示例 | 結果 |
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 |
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 |
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 nil
is 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 plain
. plain
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 %q
puts 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 n
can 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 |