跳到主內容

【Lua】【型別】 函數function

函數宣告

函數可以使用function來做宣告,並以end結束

function hello()
  print("Hello, World")
end

-- 等同以下
hello = function()
  print("Hello, World")
end

函數傳遞

function genFun()
  return function()
    print("Hello, World")
  end
end


function callFun(f)
  f()
end


local _f = genFun() -- # get a function
callFun(_f) -- print("Hello, World")

不定長參數

function hello(...)
  local members = {...}
  print("有多少成員: ", #members)
  for _,m in pairs(members) do
    print("Hello, "..m)
  end
end

-- hello("Bob", "Lua", "Luna", "Selene")
-- 有多少成員: 	4
-- Hello, Bob
-- Hello, Lua
-- Hello, Luna
-- Hello, Selene

立即呼叫函式表達式(IIFE) 與 匿名函式

(function ()
  print("Hello, World")
end)()

常用的內建函數

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

基本

  • 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