Lua中的loadfile、dofile、require详解
2016-04-01 10:29
435 查看
1.loadfile——只编译,不运行
loadfile故名思议,它只会加载文件,编译代码,不会运行文件里的代码。
比如,我们有一个hellofile.lua文件:
print(“hello”);
function hehe()
print(“hello”);
end
这个文件里有一句代码,和一个函数。试试用loadfile加载这个文件,如下代码:
loadfile("hellofile.lua");
print("end");输出结果如下:
结果表明,它是不会执行代码的。
2.dofile——执行
很明显,dofile就是会执行代码的家伙了,如下代码:
3.require——我只执行一次
require和dofile有点像,不过又很不一样,require在第一次加载文件的时候,会执行里面的代码。
但是,第二次之后,再次加载文件,则不会重复执行了。换句话说,它会保存已经加载过的文件,不会重复加载。
测试代码如下:
for i = 1, 2, 1 do
require("hellofile.lua");
end
print("end");为了说明这种情况,我刻意调用了两次require,输出结果如下:
和我们说的一样,调用了两次,但是代码只执行了一次。
如果这里换成dofile,则会输出两次hello字符串。
loadfile故名思议,它只会加载文件,编译代码,不会运行文件里的代码。
比如,我们有一个hellofile.lua文件:
print(“hello”);
function hehe()
print(“hello”);
end
这个文件里有一句代码,和一个函数。试试用loadfile加载这个文件,如下代码:
loadfile("hellofile.lua");
print("end");输出结果如下:
[LUA-print] end如果说loadfile会执行文件里的代码的话,那么,应该会输出hello字符串的。
结果表明,它是不会执行代码的。
2.dofile——执行
很明显,dofile就是会执行代码的家伙了,如下代码:
dofile("E:/Android/wordspace_cocosIDERc0/CocosLuaTest/src/hellofile.lua"); print("end");输出结果如下:
[LUA-print] hello [LUA-print] end
3.require——我只执行一次
require和dofile有点像,不过又很不一样,require在第一次加载文件的时候,会执行里面的代码。
但是,第二次之后,再次加载文件,则不会重复执行了。换句话说,它会保存已经加载过的文件,不会重复加载。
测试代码如下:
for i = 1, 2, 1 do
require("hellofile.lua");
end
print("end");为了说明这种情况,我刻意调用了两次require,输出结果如下:
[LUA-print] hello [LUA-print] end
和我们说的一样,调用了两次,但是代码只执行了一次。
如果这里换成dofile,则会输出两次hello字符串。
相关文章推荐
- Lua中的元表和元方法
- Lua内存泄漏应对方法[转]
- Lua协程(一)
- Lua初学笔记
- luajit笔记---编译成静态库以及FFI绑定宿主程序函数
- Lua FFI 实战
- C++混合编程之idlcpp教程Lua篇(4)
- lua报错,attempt to call global 'setmetatable'(a nil value)或者类似错误
- Ubuntu中vim添加lua支持
- Lua环境安装
- C2064: term does not evaluate to a function解决方法
- Seven More Languages in Seven Weeks (读书笔记):Lua
- Lua_第 20 章 IO库
- leetcode 150. Evaluate Reverse Polish Notation
- Self summary: Using Lua in torch (keep updating)
- Self summary: Using Lua in torch (keep updating)
- Self summary: Using Lua in torch (keep updating)
- Self summary: Using Lua in torch (keep updating)
- Self summary: Using Lua in torch (keep updating)
- Self summary: Using Lua in torch (keep updating)