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

lua之loadfile ,dofile, loadstring,require

2014-09-25 10:41 309 查看
先看例子:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: