iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
0
Software Development

30天 Lua重拾筆記系列 第 7

【30天Lua重拾筆記07】基礎1: 類型-數字

本文同步發表於個人網站

整數與小數

數字(number)是Lua的基礎型別之一。Lua會自動判斷是整數還是小數,會自動轉換,無明確分界。

1.0 == 1
list = {"Bob", "Lua", "Luna", "Selene"}
list[1] == list[1.0]
type(1.0) -- => number
type(1) -- => number

雖然會自動轉換,不代表沒有區別

math.type(1.0) -- => float
math.type(1) -- => integer

溢位(overflow)

Lua 5.4使用64位元的整數和浮點數(雙精度浮點數double)。

math.type(9223372036854775807) -- => integer
math.type(9223372036854775808) -- => float

這表示Lua還是有可能溢位

9223372036854775807 + 1 -- => -9223372036854775808

精度丟失

浮點數的表示也有極限,可能會有精度丟失的問題

18446744073709552111 -- => 18446744073709552000
18446744073709552000 == 18446744073709552000+100 -- => true

字串轉數字

字串轉數字使用tonumber

tonumber("1.0")

數字轉字串

相對來說數字轉字串使用tostring

tostring(1.0)

自動轉型

Lua會自動轉型,如果一個字串與數字相加,會嘗試將字串轉換為數字:

"1.0" + 2 -- => 3.0

如果一個數字和字串使用串接,會嘗試將數字轉換成字串:

"1.0"..2 -- => 1.02

偷懶轉換

知道以上規則後,可以偷點懶。

數字轉字串

1.0 .. ""

字串轉數字

"1.0" + 0

數學函式庫(math)

local math = require "math"
print(math.pi) -- => 3.1415926535898

你可以透過require "math"來使用lua本身提供的數學函式庫。require相關細節會在中級議題: 全局表(_G)、環境表(_ENV)說明。

math本身有一些基礎的數學運算和常數,包含:

  • math.abs
  • math.acos
  • math.asin
  • math.atan
  • math.ceil
  • math.cos
  • math.deg
  • math.exp
  • math.floor
  • math.fmod
  • math.huge
  • math.log
  • math.max
  • math.maxinteger
  • math.min
  • math.mininteger
  • math.modf
  • math.pi
  • math.rad
  • math.random
  • math.randomseed
  • math.sin
  • math.sqrt
  • math.tan
  • math.tointeger
  • math.type
  • math.ult

使用方式參考Lua官方說明


上一篇
【30天Lua重拾筆記06】基礎1: 變數
下一篇
【30天Lua重拾筆記08】基礎1: 類型-字串
系列文
30天 Lua重拾筆記36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言