跳到主內容

【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)()