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从调用者的角度来看,两种样式之间几乎没有区别。(一个值得一提的区别是,第一种样式使用户更难于猴子补丁该模块。根据您的观点,这是赞成还是反对。有关此的更多详细信息,请参阅EnriqueGarcía的此博客文章。Cota。)
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短