iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
0
Software Development

30天 Lua重拾筆記系列 第 11

【30天Lua重拾筆記11】基礎1: 註釋

本文同步發表於個人網站

基礎2: 註釋

--[[
{
  author = "lagagain",
  date = 20200904,
  title = "Comments of Lua code",
} 
--]]

註釋是一段永遠不會被執行的區塊。你可以在註釋區塊隨意寫任何東西,而不必遵守任何Lua的語法規則。但更好的,註釋應該是作為程式碼的部份補充。至今為止的幾天,其實也過不少註釋。像是:

------------------

阿勒? ? 這不是分隔線嗎?

單行註釋

是的,最基本的單行註釋以 -- 開頭,直至行尾都會被視為註釋。也看過:

do
  local a = 1
  local b = 2
  local sum = a + b -- sum = 1 + 2 => 3
end

或是

print("Hello, World") -- Output: Hello, World

本系列會部份以這樣方式去說明程式碼,程式碼的執行結果。不過在寫註釋時,最好是明確的補充程式碼的意義,像是:

function make_day(year, month, day)
  -- 產生localize 的 日期 字串
  ---------------------------
  -- @param(year): integer year
  -- @param(month): integer month
  -- @param(day): integer day
  --
  -- @return: string localized date string
	return year .. "年" .. month .. "月" .. day .. "日"
end

today = make_day(2020, -- year
                 9,    -- month
                 14)   -- day

上面說明make_day函數的作用、參數類型說明與回傳值。並且在使用時,亦把帶入的引數說明帶入的意義。

多行註釋

--[[
                      _oo0oo_
                     o8888888o
                     88" . "88
                     (| -_- |)
                     0\  =  /0
                   ___/`---'\___
                 .' \\|     |// '.
                / \\|||  :  |||// \
               / _||||| -:- |||||- \
              |   | \\\  -  /// |   |
              | \_|  ''\---/''  |_/ |
              \  .-\__  '-'  ___/-. /
            ___'. .'  /--.--\  `. .'___
         ."" '<  `.___\_<|>_/___.' >' "".
        | | :  `- \`.;`\ _ /`;.`/ - ` : | |
        \  \ `_.   \_ __\ /__ _/   .-` /  /
    =====`-.____`.___ \_____/___.-`___.-'=====
                      `=---='

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

              佛祖保佑         永无BUG
  --]]

除了簡單單行註釋,Lua也像C有/*comment*/這樣的多行註釋。寫法是--[[comment--]]。實際上與多行文字的規則一樣。可以在[[]]加入任意相同數量的=來配對。如下面是全都是註釋:

--[===[
Some Comments
==============
特別插入--]]  但實際註釋還未結束
--]===]

上面註釋直到--]===]才結束。之後還未換行的內容,不是註釋區塊。

--[===[
Some Comments
==============
特別插入--]]  但實際註釋還未結束
--]===] print("這段不是註釋") -- end comment

如果註釋內需要--]],你可以用任意數量的=配對來處理。

巢狀註釋

透過多行註釋配對,Lua是可以支援巢狀結構的,可以這樣寫:

--[==[ 外部註釋開始
  -- outer comment
  print("Hello")
  --[=[ 內部註釋開始
      inner comment
  --]=] -- 內部註釋結束
  print("World")
--]==] -- 外部註釋截截住

可以很簡單的將註釋內的print("World")變得不是註釋:

--[==[ 註釋開始
  -- outer comment
  print("Hello")
  --[=[ 註釋內部
      inner comment
  --]==] -- 註釋結束
  print("Hello")
--]==] -- 單行註釋

也可以很輕易的啟用外部區塊

---[==[ 變成單行註釋
  -- outer comment
  print("Hello")
  --[=[ 內部註釋開始
      inner comment
  --]=] -- 內部註釋結束
  print("World")
--]==] -- 變成單行註釋

上一篇
【30天Lua重拾筆記10】基礎1: 類型-布林和nil
下一篇
【30天Lua重拾筆記12】基礎2: 控制 - 條件
系列文
30天 Lua重拾筆記36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言