隨手扎
【30天Lua重拾筆記18】基礎2: 應該知道的(總集+補充)
關於變數
- 值(value)有型別;變數(varible)沒有
- 基礎型別一共有8個
nil
boolean
number
string
function
userdata
thread
table
- table是唯一的複合型別(之後會提到)
- Lua 5.4之後,可以為變數標記屬性。Lua 5.4支援
const
和close
兩種屬性 - 變數預設是全局變數(實際上與特殊變數
_ENV
和_G
有關,之後會提到) - 變數值型別會自動轉型,但不該依賴
數字
- 整數和浮點數會自動轉換
- 整數有範圍,有溢位問題
- 浮點數也有精度丟失的問題
布林
- 只有
nil
和false
為假,其他為真 0
、空字串、空表亦為真
控制結構
- 有label &
goto
- label只屬於當前函式區塊
- 使用
elseif
,而非else if
(這點我覺得C就設計的比較漂亮)- 嵌套使用
if
(else if
),記得補上end
- 嵌套使用
- 非強求,但最好做好排版
函數
- 函數定義是語法糖
- 函數是一等公民(第一類別)
- 函數呼叫如果是單一字面字串或是單一字面表格時,可以審略括號。(和Kotlin、Ruby有點像阿)
註釋
- 註釋可以嵌套使用
常用的內建函數
其實除此之外,還有很多應該是很常用的。不過先放個已經提到過,或是大概不會提到的。
基本
- ipairs
- pairs
- require
- tonumber
- tostring
- type
輸入/輸出
估計本系列不怎麼會提到,先放這XD。
- io.close
- io.input
- io.lines
- io.open
- io.output
- io.popen
- io.read
- io.stderr
- io.stdin
- io.stdout
- io.tmpfile
- io.type
- io.write
- file:close
- file:flush
- file:lines
- file:read
- file:seek
- file:write
哈…好像幾乎都蠻重要的…
數學
- math.abs
- math.ceil
- math.exp
- math.floor
- math.huge (無限大)
- math.log
- math.max
- math.maxinteger
- math.min
- math.mininteger
- math.pi (PI 常數)
- math.random
- math.randomseed
- math.tointeger
- math.type
作業系統
- os.clock
- os.date
- os.difftime
- os.execute
- os.exit
- os.getenv
- os.time
Lua 5.1前一個和
os.getenv
很像的函數setfenv
其實也蠻常用的,後來被移除,改用其他方式。
當前還有很多是使用Lua 5.1,這雖然是需要知道的事情,不過其實其與作業系統無關。
字串
- string.byte
- string.char
- string.find
- string.format
- string.len
- string.reverse
- string.sub
- utf8.char
- utf8.codes
- utf8.len