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
- lua模块的几种实现方式
- Lua table 的几种创建方式。
- lua模块几种形式
- 五角星评分和分数展示模块的几种实现方式
- lua中遍历table的几种方式比较
- cocos2dx-lua捕获用户touch事件的几种方式
- Lua基础:table的几种构造方式
- lua中遍历table的几种方式比较
- lua中遍历table的几种方式比较
- lua中遍历table的几种方式比较
- cocos2dx-lua捕获用户touch事件的几种方式
- lua中遍历table的几种方式比较
- ngx lua获取时间戳的几种方式
- lua cocos 创建动画的几种方式
- Python模块常用的几种安装方式
- Python模块常用的几种安装方式
- python 模块常用的几种安装方式
- Python模块常用的几种安装方式
- 使用Spring的注解方式实现AOP
- 第七届河南省赛 zzuoj 10403: D.山区修路 (DP转换&&技巧)
- Sublime Text 3插件安装
- mina 心跳机制
- 【iOS】OC总结
- lua模块的几种实现方式
- 多线程断点下载
- android post提交数据
- Android studio提交SVN需要忽略的文件
- 设计模式—装饰器模式(Decorator)
- leetcode 做题记录
- Jetty实战之 安装 运行 部署
- ORACLE内存管理简述1
- php高级函数【递归函数】