Lua中的loadfile、dofile、loadstring、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函數(shù)像dofile一樣載入文件為一個Chunk并執(zhí)行。但具有兩個好處:1. 按模式加載文件 2.不會重復(fù)載入相同的文件。
require的參數(shù)是一個完整的文件名(目錄名+文件名,可能有點類似于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
所以,如果要執(zhí)行當(dāng)前目錄的test.lua文件,我們只需要require("test")即可,但是如果我們要執(zhí)行另一個目錄下的文件,比如"D:\lua\a.lua",我們就需要將這個路徑加入到package.path當(dāng)中,例如我們可以這樣寫:
package.path=package.path .. ";D:\?.lua"
這樣我們就可以使用require函數(shù)了,比如require("a").
注:require只會被加載一次。
for callCount = 0, 2 do
require("test");
end
相關(guān)文章
Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務(wù)器的時間)
這篇文章主要介紹了Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務(wù)器的時間),本文使用Lua作為客戶端獲取網(wǎng)絡(luò)上的一些授時服務(wù)提供商的時間,需要的朋友可以參考下2015-04-04