当前位置: 首页 > 编程笔记 >

Lua 编写模块

惠野
2023-03-14
本文向大家介绍Lua 编写模块,包括了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。)

 类似资料:
  • 生气却不可犯罪,不可含怒到日落,也不可给魔鬼留地步。从前偷窃的,不要再偷。总要劳力,亲手作正经事,就可有余,分给那缺少的人。污秽的言语,一句不可出口,只要随事说造就人的好话,叫听见的人得益处。(EPHESIANS 4:26-29) 随着对Python学习的深入,其优点日渐突出,让读者也感觉到Python的强大了。这种强大体现在“模块自信”上,因为Python不仅有很强大的自有模块(标准库),还有海

  • 经典的 "Hello world" 的程序总是被用来开始介绍一种语言。在 Lua 中,写一个这样的程序很简单: print("Hello world") 在 Lua 中,语句之间可以用分号 ";" 隔开,也可以用空白隔开。一般来说,如果多个语句写在同一行的话,建议总是用分号隔开。 Lua 有好几种程序控制语句,如: 条件控制: if 条件 then … elseif 条件 then … else

  • nodejs的出现,可以算是前端里程碑式的一个事件,它让前端攻城狮们摆脱了浏览器的束缚,踏上了一个更加宽广的舞台。前端的可能性,从此更加具有想象空间。 随着一系列基于nodes的应用/工具的出现,工作中与nodejs打交道的机会越来越多。无论在node应用的开发,还是使用中,包管理都扮演着一个很重要的作用。NPM(node package manager),作为node的包管理工具,极大地便利了我

  • 本文向大家介绍编写高性能Lua代码的方法,包括了编写高性能Lua代码的方法的使用技巧和注意事项,需要的朋友参考一下 前言 Lua是一门以其性能著称的脚本语言,被广泛应用在很多方面,尤其是游戏。像《魔兽世界》的插件,手机游戏《大掌门》《神曲》《迷失之地》等都是用Lua来写的逻辑。 所以大部分时候我们不需要去考虑性能问题。Knuth有句名言:“过早优化是万恶之源”。其意思就是过早优化是不必要的,会浪费

  • 如何为tarantool编写一个lua程序,它将在后台定期执行一些任务(例如每10分钟一次)?

  • 问题内容: 我正在第一个NPM模块上工作。之前,我曾短暂地使用过Typescript,但一个大问题是,对于许多模块,没有可用的定义文件。因此,我认为用打字稿编写模块是一个好主意。 但是,我找不到有关最佳方法的任何信息。我发现了一个相关的问题“ 我可以在coffeescript中编写npm软件包吗? ”,那里的人们建议只发布javascript文件。但是与coffeescript文件相比,如果在打字