您的位置:首页 > 编程语言 > Lua

lua loadfile dofile require

2016-07-01 18:53 381 查看
1.loadfile    ——只编译,不运行
hellofile.lua文件

print(“hello”);

function hehe()
print(“hello”);

end

loadfile("hellofile.lua");

print("end");

[LUA-print] end

2.dofile   ——执行
dofile("E:/Android/wordspace_cocosIDERc0/CocosLuaTest/src/hellofile.lua");

print("end");

[LUA-print] hello

[LUA-print] end

这里有点尴尬,文件路径我用了绝对路径,因为dofile在Coco Code IDE里使用相对路径会找不到文件(即使使用了addSearchPath

3.require   ——我只执行一次
require和dofile有点像,不过又很不一样,require在第一次加载文件的时候,会执行里面的代码。

但是,第二次之后,再次加载文件,则不会重复执行了。换句话说,它会保存已经加载过的文件,不会重复加载。

for i = 1, 2, 1 do
require("hellofile.lua");

end

print("end");

[LUA-print] hello

[LUA-print] end

和我们说的一样,调用了两次,但是代码只执行了一次。

如果这里换成dofile,则会输出两次hello字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: