數字教學 |
|
有些語言預設支援下列一種或多種數字類型
版本 5.3 新增了對整數的支援(數字可以是整數),但是以下大部分資訊並未失效,因為必要時會進行強制轉型。
為了簡潔起見,Lua 只支援一種數字類型:浮點數。這些數字預設是雙精度浮點數。然而,如果您需要,Lua 可以重新編譯後支援單精度浮點數。如果您不熟悉浮點數,建議您閱讀 浮點 數字。
最需要記得的是,如果您對數字使用小數部分(或除法),它們可能會產生捨入誤差。
此外,在十進制中有無限循環模式的數字在二進制中可能沒有,因此請不要假設任何小數都是「安全的」。最需要記得的是,不要對小數使用 ==
算子,因為它會檢查完美的相等性。另一件需要記得的是,要撰寫您的程式碼,這樣捨入誤差才不會長時間累積成大量的誤差。
如果您的數字是整數(沒有小數部分),而且它們不會超過 2^63,那麼您就不用擔心這些問題。
我們可以用 Lua 互動式指令列提示字元在表達式前加上 =
來使用它當作計算器,例如:
Lua 5.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio > = 1 1 > = 1 + 2 3 > = 3.1415927 3.1415927 > = 5 / 6 0.83333333333333
<value>e<exponent>
或 <value>E<exponent>
形式表示數字的指數類型,即表示為 <value> * 10 ^ <exponent>
。> = 1.2345e6 1234500 > = 543.21E8 54321000000 > = 2.56e-4 0.000256
> width = 7.5
> height = 12.7
> = width * height
95.25
> depth = 2.8
> area = width * height
> volume = area * depth
> print(area, volume)
95.25 266.7
Lua 有附帶 math 函式庫(參閱參考手冊第 5.6 段 [1])。提供的函式如下
math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.floor math.fmod math.frexp math.ldexp math.log math.log10 math.max math.min math.modf math.pow math.rad math.random math.randomseed math.sin math.sinh math.sqrt math.tan math.tanh
> = math.sqrt(101) 10.049875621121 > = math.pi 3.1415926535898 > = math.sin( math.pi/3 ) 0.86602540378444
您可以使用 tonumber()
函式將字串轉換為數字。它會接受一個字串引數並回傳一個數字。
> = tonumber("123") + 25 148 > x = tonumber("123.456e5") > print(x) 12345600
對於將整數轉換為浮點數,這個運算會回傳已轉換整數的十進制格式
> = (16 ^ 13) + 10 - (16 ^ 13) 10.0
Lua 會自動轉換字串和數字型態以執行運算。例如:若您嘗試將算術運算套用在字串上,Lua 會先嘗試將該字串轉換為數字。否則,運算將無法執行。若無法將字串轉換為數字時,會產生錯誤。這類型別的自動轉換稱為強制轉換。
> = 100 + "7" 107 > = "1000" + 234 1234 > = "hello" + 234 stdin:1: attempt to perform arithmetic on a string value stack traceback: stdin:1: in main chunk [C]: ? > = 234 + "1000" 1234
"hello"
無法轉換為數字,因此發生錯誤。在靜態類型語言(例如 C)中,這將導致錯誤,因為您無法在未進行強制轉型的狀況下,將值指定給不相容型態的變數。這種情況在 Lua 中可行,這是因為它是動態類型。值得注意的例外:比較運算子(== ~= < > <= >=
)不會強制轉換其引數。(不)等於運算子會將數字視為不等於其字串表示式(或實際上任何非數字型態)。當您提供給排序運算子不同型態時,將會產生錯誤。
> = 100 == "100" false > = 100 ~= "hello" true > = 100 ~= {} true > = 100 == tonumber("100") true > = 100 <= "100" stdin:1: attempt to compare number with string stack traceback: stdin:1: in main chunk [C]: ?