源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Lua中的loadfile、dofile、loadstring、require用法实例

  • 时间:2020-01-23 05:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Lua中的loadfile、dofile、loadstring、require用法实例
[u]复制代码[/u] 代码如下:
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只会被加载一次。
[u]复制代码[/u] 代码如下:
 for callCount = 0, 2 do   require("test");  end
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部