Examples of LoadFile, Dofile, loadstring, require usages in Lua _lua

Source: Internet
Author: User
Tags lua

Copy Code code as follows:

Todo
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 is 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
In Lua, the Require function loads a file as a chunk and executes like dofile. But it has two advantages: 1. Load file 2 in mode. The same file will not be loaded repeatedly.
The Require parameter is a complete file name (directory name + filename, possibly somewhat similar to Java package), i.e. Package.path, the typical Package.path value is as follows (where D:\Bin is the Lua.exe directory):
.\?. Lua;d:\bin\lua\? Lua;d:\bin\lua\?\init.lua;d:\bin\? Lua;d:\bin\?\init.lua
The directory that is usually useful to us is. \? Lua
So, if you want to execute the Test.lua file for the current directory, we just need require ("test"), but if we're going to execute a file in another directory, like "D:\lua\a.lua", We need to add this path to the Package.path, for example we can write:
Package.path=package.path.. ";D: \?" Lua
So we can use the Require function, such as require ("a").
Note: Require will only be loaded once.

Copy Code code as follows:

For callcount = 0, 2 do
Require ("test");
End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.