サーチ…


備考

モジュールを書くための基本的なパターンは、関数名であるキーと関数そのものの値でテーブルを塗りつぶすことです。モジュールは、この関数を呼び出して、 requireとuseのコードを呼び出します。 (関数はLuaのファーストクラスの値なので、テーブルに関数を格納するのは簡単で一般的です)。テーブルには、文字列や数値などの重要な定数を含めることもできます。

モジュールの作成

--- 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

発信者の視点からは、2つのスタイルの違いはほとんどありません。 (1つの相違点は、最初のスタイルではユーザーがモジュールをモンキー編集するのがより難しくなるということです。これは、あなたの視点に応じてプロまたはコンです。詳細については、EnriqueGarcíaのこのブログ記事を参照してください。 Cota。)

モジュールの使用

-- 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