lua
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package1 = {}

package1.const = "测试常量"


function package1.func1()
    io.write("this is public func\n")
end

return package1

req.lua

lua
1
2
3
require "package1"
package1.func1()
print(package1)
text
1
2
3
lc@lc-virtual-machine:~/lua$ lua pack1.lua 
this is public func
table: 0x5575766224a0

注意事项:

  • 测试文件是和封装好的模块在同一个目录,否则引用时需要设置路径。

    lua
    1
    2
    3
    4
    5
    6
    7
    
    package.path = '/home/lc/lua/1/package1.lua;';
    
    require "package1"
    
    package1.func1()
    
    print(package1)
  • 模块名称和文件名称必须相同