수색…


비고

모듈을 작성하는 기본 패턴은 함수 이름 인 키와 함수 자체의 값으로 테이블을 채우는 것입니다. 그런 다음 모듈은 require 및 use 코드를 호출하는이 함수를 반환합니다. (함수는 루아에서 제일 (first-class) 값이므로 테이블에 함수를 저장하는 것은 쉽고 일반적입니다.) 테이블은 문자열이나 숫자의 형태로 중요한 상수를 포함 할 수 있습니다.

모듈 작성하기

--- trim: a string-trimming module for Lua
-- Author, date, perhaps a nice license too
--
-- The code here is taken or adapted from  material in
-- Programming in Lua, 3rd ed., Roberto Ierusalimschy

-- trim_all(string) => return string with white space trimmed on both sides 
local trim_all = function (s)
  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end

-- trim_left(string) => return string with white space trimmed on left side only
local trim_left = function (s)
  return (string.gsub(s, "^%s*(.*)$", "%1"))
end

-- trim_right(string) => return string with white space trimmed on right side only
local trim_right = function (s)
  return (string.gsub(s, "^(.-)%s*$", "%1"))
end

-- Return a table containing the functions created by this module
return {
  trim_all = trim_all,
  trim_left = trim_left,
  trim_right = trim_right
}

위의 방법에 대한 또 다른 접근법은 최상위 테이블을 작성한 다음 그 안에 함수를 직접 저장하는 것입니다. 그 관용구에서 위의 모듈은 다음과 같습니다.

-- A conventional name for the table that will hold our functions
local M = {}

-- M.trim_all(string) => return string with white space trimmed on both sides
function M.trim_all(s)
  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end

-- M.trim_left(string) => return string with white space trimmed on left side only
function M.trim_left(s)
  return (string.gsub(s, "^%s*(.*)$", "%1"))
end

-- trim_right(string) => return string with white space trimmed on right side only
function M.trim_right(s)
  return (string.gsub(s, "^(.-)%s*$", "%1"))
end


return M

호출자의 관점에서 보았을 때 두 스타일 사이에는 약간의 차이가 있습니다. (언급 할 가치가있는 한 가지 차이점은 첫 번째 스타일은 사용자가 모듈을 monkeypatch하는 것을 더 어렵게 만듭니다. 이것은 여러분의 관점에 따라 pro 또는 con 중 하나입니다. 이에 대한 자세한 내용은 Enrique García의 블로그 게시물 을 참조하십시오. 코타.)

모듈 사용하기

-- The following assumes that trim module is installed or in the caller's package.path,
-- which is a built-in variable that Lua uses to determine where to look for modules.
local trim = require "trim"

local msg = "    Hello, world!      "
local cleaned = trim.trim_all(msg)
local cleaned_right = trim.trim_right(msg)
local cleaned_left = trim.trim_left(msg)

-- It's also easy to alias functions to shorter names.
local trimr = trim.trim_right
local triml = trim.trim_left


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow