1. 使用module , require方法
"my_test1.lua"内容如下
module("my_test1", package.seeall);
function add(a, b)
return a + b;
end
function hello()
print("it is ok...");
end
在另一个文件 my_test4.lua 调用my_test1.lua 里的函数
内容如下
require "my_test1"
my_test1.hello();
---------------------------------------------------
上述requier只能从磁盘加载 "my_test1.lua"。一般做游戏时lua文件都是打包的,要从内存加载就不行了。
我们可以用 loadstring 来实现
loadstring(
[[module("mm1", package.seeall);
function hello()
print ("test mm1 from my_test3 ok.");
end]]
)()
require "mm1"
mm1.hello();
或者在程序里导出全局接口.....
注意loadstring的结果是个函数,loadstring本身不会执行代码的,后面加个()执行一下才能用,否则requeire找不到mm1。