zoukankan      html  css  js  c++  java
  • Lua中模块初识

    定义了两个文件:

    Module.lua 和 main.lua

    其中,模块的概念,使得Lua工程有了程序主入口的概念,其中main.lua就是用来充当程序主入口的。

    工程截图如下:

     

    Module.lua中代码:

     1 --模块类似于一个封装库
     2 --可以把一些公用的代码放在一个文件里,以 API 接口的形式在其他地方调用,有利于代码的重用和降低代码耦合度。
     3 --Lua 的模块是由变量、函数等已知元素组成的 table,因此创建一个模块很简单,就是创建一个 table,
     4 --然后把需要导出的常量、函数放入其中,最后返回这个 table 就行
     5 
     6 --模块定义
     7 module = {}
     8 
     9 --定义常量
    10 module.constant = "the value is constant"
    11  
    12 --public函数定义
    13 function module.func1()
    14     io.write("func1 is public! 
    ")
    15 end
    16 
    17 --private函数定义
    18 local function func2()
    19     print("func2 is private")
    20 end
    21 
    22 
    23 function module.func3()
    24     func2()
    25 end
    26 
    27 return module

    main.lua中代码:

    --加载模块
    --执行 require 后会返回一个由模块常量或函数组成的 table,并且还会定义一个包含该 table 的全局变量
    require "Module"
    
    module.func3();
    
    --[[
    执行结果:
    func2 is private
    --]]
    
    --也可以给加载进来的模块起别名
    local moduleTest = require "module"
    moduleTest.func1()
    
    --[[
    执行结果:
    func1 is public! 
    --]]
    
    print(package.path)
    print(package.cpath)

    参考:http://www.runoob.com/lua/lua-modules-packages.html

    码云上的相关工程:https://gitee.com/luguoshuai/LearnLua

  • 相关阅读:
    主外键 子查询
    正则表达式
    css3 文本效果
    css3 2d
    sql 基本操作
    插入 视频 音频 地图
    j-query j-query
    document
    js dom 操作
    js
  • 原文地址:https://www.cnblogs.com/luguoshuai/p/9219837.html
Copyright © 2011-2022 走看看