模組定義

lua-users home
wiki

有很多方法可以在 Lua 中定義「模組」[1]

從資料表

-- mymodule.lua
local M = {} -- public interface

-- private
local x = 1
local function baz() print 'test' end

function M.foo() print("foo", x) end

function M.bar()
  M.foo()
  baz()
  print "bar"
end

return M

-- Example usage:
local MM = require 'mymodule'
MM.bar()

這是一種常見的方法。它很簡單,不依賴外部程式碼,避免使用全域變數,而且陷阱很少。外部變數會加上「M.」前綴,看得一清二楚。

另請參閱


最近變更 · 喜好設定
編輯 · 歷程
上次編輯時間為 2015 年 2 月 19 日下午 6:01 GMT (差異)