Lua Module Definition by 신동호

참조 문서: http://lua-users.org/wiki/ModuleDefinition

Lua 에서 "module" 을 정의하는 방법은 다양합니다.

From a Table

-- 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 이라는 인터페이스(테이블)을 통해서만 접근할 수 있습니다.

Using the module Function

module(..., package.seeall)  -- optionally omitting package.seeall if desired

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

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

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

-- Example usage:
require 'mymodule'
mymodule.bar()

이 방법은 간단해서 Programming in Lua 에도 소개되어 있는 방법입니다만, 치명적인 문제점을 가지고 있습니다. LuaModuleFunctionCritiqued(http://lua-users.org/wiki/LuaModuleFunctionCritiqued) 를 참조하세요.

From a Table - Using Locals Internally

local M = {}

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

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

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

return M

이 방법은 테이블을 사용한 접근 방법과 비슷해 보입니다.  이 방식은 좀 더 문맥적으로 혼동스럽긴 하지만, 테이블을 이용한 접근 방법보다 속도가 중요하거나 보다 유연한 코드를 만들어 내는 데 유용합니다.(DetectingUndefinedVariables) 나아가 이 접근 방법은 모듈 안에서 만들어진 내용을 외부에서 변경할 수 도 있습니다.

localmodule

local M = {}

local x = 1  -- private

local M_baz = 1  -- public

local function M_foo()
  M_baz = M_baz + 1
  print ("foo", x, M_baz)
end

local function M_bar()
  M_foo()
  print "bar"
end

require 'localmodule'.export(M)

return M

-- Example usage:
local MM = require 'mymodule'
MM.baz = 10
MM.bar()
MM.foo = function() print 'hello' end
MM.bar()

-- Output:
-- foo     1       11
-- bar
-- hello
-- bar

이 방법은 보다 서술적으로 보입니다. 'localmodule' 을 사용하면 _ 기호를 사용하여 모듈을 적절하게 패킹할 수 있습니다.


트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://aronze.egloos.com/tb/1416146 [도움말]

덧글

덧글 입력 영역