--- 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
从调用者的角度来看,两种样式之间几乎没有区别。(一个值得一提的区别是,第一种样式使用户更难于猴子补丁该模块。根据您的观点,这是赞成还是反对。有关此的更多详细信息,请参阅EnriqueGarcía的此博客文章。 Cota。)