iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0
Software Development

30天 Lua重拾筆記系列 第 18

【30天Lua重拾筆記18】基礎2: 應該知道的(總集+補充)

同步發表於個人網站

沒想到會剛好在中秋連假發表小總集。
不知道能不能在連假把最後打算寫的幾篇寫完...

關於變數

  • 值(value)有型別;變數(varible)沒有
  • 基礎型別一共有8個
    1. nil
    2. boolean
    3. number
    4. string
    5. function
    6. userdata
    7. thread
    8. table
  • table是唯一的複合型別(之後會提到)
  • Lua 5.4之後,可以為變數標記屬性。Lua 5.4支援constclose兩種屬性
  • 變數預設是全局變數(實際上與特殊變數_ENV_G有關,之後會提到)
  • 變數值型別會自動轉型,但不該依賴

數字

  • 整數和浮點數會自動轉換
  • 整數有範圍,有溢位問題
  • 浮點數也有精度丟失的問題

布林

  • 只有nilfalse為假,其他為真
  • 0、空字串、空表亦為真

控制結構

  • 有label & goto
  • label只屬於當前函式區塊
  • 使用elseif,而非else if (這點我覺得C就設計的比較漂亮)
    • 嵌套使用if(else if),記得補上end
  • 非強求,但最好做好排版

函數

  • 函數定義是語法糖
  • 函數是一等公民(第一類別)
  • 函數呼叫如果是單一字面字串或是單一字面表格時,可以審略括號。(和Kotlin、Ruby有點像阿)

註釋

  • 註釋可以嵌套使用

常用的內建函數

其實除此之外,還有很多應該是很常用的。不過先放個已經提到過,或是大概不會提到的。

基本

  • ipairs
  • pairs
  • print
  • 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

上一篇
【30天Lua重拾筆記17】基礎2: pcall, xpcall, load (eval, exec, apply)
下一篇
【30天Lua重拾筆記29】物件導向 之 HoloLive 炎上! 桐生可可&赤井心 禁足三周
系列文
30天 Lua重拾筆記36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言