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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-21 我要评论
想了解Lua中的loadfile、dofile、loadstring、require用法实例的相关内容吗,在本文为您仔细讲解Lua loadfile、dofile、loadstring、require实例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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函数像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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们