lua模块的几种实现方式

来源:互联网 发布:windows损坏文件 编辑:程序博客网 时间:2024/05/20 16:35

 
lua模块的几种实现方式


1.一种是大家比较常见的比较简单的实现方式:利用table实现,最后返回这个table变量。


---- Created by IntelliJ IDEA.-- User: sdcuike-- Date: 2016/1/2-- Time: 15:10-- To change this template use File | Settings | File Templates.----[[The simplest way to create a module in Lua is really simple: we create a table,put all functions we want to export inside it, and return this table.  --]]local M = {}function M.add(a,b)    return a + b;endreturn M


2.第二种实现方式:这种方式主要和第一种方式的区别是不用返回table变量。


---- Created by IntelliJ IDEA.-- User: sdcuike-- Date: 2016/1/2-- Time: 11:19-- To change this template use File | Settings | File Templates.----[[ Some people do not like the final return statement. One way of eliminatingit is to assign the module table directly into package.loaded:  --]]local M = {}package.loaded[...] = Mfunction M.add(a,b)    return a + bend


3.第三种实现方式:主要是利用环境变量避免全局变量的污染。


---- Created by IntelliJ IDEA.-- User: sdcuike-- Date: 2016/1/2-- Time: 15:38-- To change this template use File | Settings | File Templates.----[[ One drawback of those basic methods for creating modules is that it is all tooeasy to pollute the global space, for instance by forgetting a local in a privatedeclaration.Environments offer an interesting technique for creating modules that solvesthis problem. Once the module main chunk has an exclusive environment, notonly all its functions share this table, but also all its global variables go to thistable. Therefore, we can declare all public functions as global variables and theywill go to a separate table automatically. All the module has to do is to assignthis table to the _ENV variable.  --]]local M = {}_ENV = Mfunction add(a,b)    return a + bendreturn M


测试一下:


---- Created by IntelliJ IDEA.-- User: sdcuike-- Date: 2016/1/2-- Time: 11:22-- To change this template use File | Settings | File Templates.--local b = require("BasicModule")local SM = require("SimplestWayToCreateModule")local EM = require("EnvModule")print(b.add(1,2)) --3print(SM.add(3,6)) --9print(EM.add(10,10))  --20


1 0
原创粉丝点击