lua之loadfile ,dofile, loadstring,require
2014-09-25 10:41
309 查看
先看例子:
require:
在lua中,require函数像dofile一样载入文件为一个Chunk并执行。但具有两个好处:1. 按模式加载文件 2.不会重复载入相同的文件。
require的参数是一个完整的文件名(目录名+文件名,可能有点类似于java中的包吧),即package.path,典型的package.path值如下(其中D:\Bin为lua.exe所在目录):
.\?.lua;D:\Bin\lua\?.lua;D:\Bin\lua\?\init.lua;D:\Bin\?.lua;D:\Bin\?\init.lua
通常对我们有用的目录是.\?.lua
所以,如果要执行当前目录的test.lua文件,我们只需要require("test")即可,但是如果我们要执行另一个目录下的文件,比如"D:\lua\a.lua",我们就需要将这个路径加入到package.path当中,例如我们可以这样写:
package.path=package.path .. ";D:\?.lua"
这样我们就可以使用require函数了,比如require("a").
注:require只会被加载一次。
do local errorInfo = loadfile("test.lua"); --load code file if(errorInfo == nil) then print("load file failed"); else print("load file success"); local doInfo = dofile("test.lua") --complie the file and execute the file if(doInfo == 0) then print("run file failed"); else print("run file scuess"); end end --local i = 0;--it must be global var, the loadstring only call the global var i = 0; local f = loadstring("i = i + 1"); f(); print(i); g = function() i = i + 1; --it can call the local and the global var end g(); print(i); end
require:
在lua中,require函数像dofile一样载入文件为一个Chunk并执行。但具有两个好处:1. 按模式加载文件 2.不会重复载入相同的文件。
require的参数是一个完整的文件名(目录名+文件名,可能有点类似于java中的包吧),即package.path,典型的package.path值如下(其中D:\Bin为lua.exe所在目录):
.\?.lua;D:\Bin\lua\?.lua;D:\Bin\lua\?\init.lua;D:\Bin\?.lua;D:\Bin\?\init.lua
通常对我们有用的目录是.\?.lua
所以,如果要执行当前目录的test.lua文件,我们只需要require("test")即可,但是如果我们要执行另一个目录下的文件,比如"D:\lua\a.lua",我们就需要将这个路径加入到package.path当中,例如我们可以这样写:
package.path=package.path .. ";D:\?.lua"
这样我们就可以使用require函数了,比如require("a").
注:require只会被加载一次。
for callCount = 0, 2 do require("test"); end
相关文章推荐
- Lua中的loadfile、dofile、loadstring、require用法实例
- 【lua的require、dofile、loadfile、loadstring及luamodule机制】
- Lua的loadfile、dofile、loadstring、require
- Lua中require,dofile,loadfile,dostring,loadstring,loadlib,load之间的区别
- 三、Lua中require,dofile,loadfile,dostring,loadstring,loadlib,load之间的区别
- Lua中的loadfile、dofile、require详解
- Lua中的loadfile,dofile,require使用,最后还有调试
- Lua 加载函数require dofile loadfile
- Lua中的loadfile、dofile、require详解
- Lua中的loadfile、dofile、require详解
- Lua中的loadfile、dofile、require详解
- lua中dofile,loadfile,require的区别
- dofile, loadfile, loadstring, require, module
- lua require dofile loadfile区别
- Lua知识点_基础_loadfile和dofile和require
- lua require dofile loadfile区别
- Lua中的loadfile、dofile、require详解
- lua require dofile loadfile 比较笔记
- Lua中的loadfile、dofile、require详解
- Lua中的loadfile、dofile、require详解