Lua中的loadfile、dofile、loadstring、require用法執行個體_Lua

來源:互聯網
上載者:User

複製代碼 代碼如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.