number 數據類型,或 double,表示一個 雙精度 (64 位) 浮點數。數字範圍從 -1.7 * 10308 到 1.7 * 10308(約 15 位精度,正負皆可)。
有符號和無符號
數字的符號表明它是正數還是負數。例如,1 是正數,而 -1 是負數。在 Luau 中,數字 -0 等於 0。
print(0 == -0) --> trueprint(-0 > 1) --> falseprint(-0 < 1) --> trueprint(-0 > -1) --> trueprint(-0 < -1) --> false
數字分類
Luau 不區分整數和數字,但 API 參考有時會區分它們,以更具體地說明如何使用每個 API。
float
float 數字類型指的是一個有小數點的實數。在計算機科學術語中,它們是 單精度 (32 位) 浮點數,這種數字的精度不及雙精度浮點數,但對大多數用例來說足夠精確,並且需要的記憶體和儲存空間較少。
int
integer 數字類型,或 int,指的是一個 32 位整數,範圍從 -231 到 231 - 1。期望整數的屬性和函數可能會自動進行四捨五入或在賦值或傳遞非整數時引發錯誤。
int64
int64 數字類型指的是一個有符號的 64 位整數,範圍從 -263 到 263 - 1。這種類型的整數通常用於使用來自 Roblox 網站的 ID 數字的方法。例如,Player.UserId 是一個 int64,而 MarketplaceService:PromptPurchase() 和 TeleportService:Teleport() 兩者的 ID 參數均期望 int64。
表示法
數字的表示方式是先寫最重要的數字(大端法)。在 Luau 中,有多種方法可以表示數字字面量:
操作
您可以使用邏輯和關聯 運算符 來操作和比較數字。您還可以在 math 庫中使用數學函數,如 math.sqrt() 和 math.exp(),以及在 bit32 庫中使用位運算。
類型自省
您可以通過使用 type(x) 或 typeof(x) 來確定值 x 是否為數字。如果 x 是數字,則兩者都會返回字符串 number。
local testInt = 5local testDecimal = 9.12761656local testString = "Hello"print(type(testInt)) --> numberprint(type(testDecimal)) --> numberprint(type(testString)) --> stringprint(typeof(testInt)) --> numberprint(typeof(testDecimal)) --> numberprint(typeof(testString)) --> string
四捨五入函數
您可以使用 math.floor()、math.ceil() 或 math.modf() 來四捨五入數字。如果 Luau 能夠將結果表示為整數,則這些函數將返回整數結果。如果數字太大,Luau 將其作為浮點數返回。
- 要確定數字 x 是否為整數,使用 math.floor(x) == x。
- 要向下四捨五入數字,使用 math.floor()。
- 要向上四捨五入數字,使用 math.ceil()。
- 要向零四捨五入數字,使用 math.modf()。它還將返回作為第二個結果的四捨五入數字的分數差。
print(math.floor(3.3)) --> 3print(math.floor(-3.3)) --> -4print(math.ceil(3.3)) --> 4print(math.ceil(-3.3)) --> -3print(math.modf(3.3)) --> 3 0.2999999999999998print(math.modf(-3.3)) --> -3 -0.2999999999999998