Difference between Lua dofile LoadFile loadstring

Source: Internet
Author: User

Dofile, which is treated as a primitive operation of the chunk that Lua runs the code.


1. Dofile is actually a helper function. The function that truly completes the function is LoadFile;


2. Unlike dofile, LoadFile compiles the code into an intermediate code and returns the compiled chunk as a function without executing the code;






3. LoadFile does not throw an error message but returns an error code.



Change print. Lua in testmain to otherprint. Lua (The Lua file does not exist). The result is as follows: LoadFile returns the error code and error message, but dofile throws an exception, so it does not print ---------- B -----------


4. LoadFile only needs to be compiled once and can be run multiple times; dofile needs to be compiled every time (applicable to simple functions ).



Based on the above four items, we can consider LoadFile as defined in this way:

  


Lua treats each chunk as an anonymous function:

Suppose we have a file Foo. Lua:


 

After the command F = LoadFile ("foo. Lua") is executed, foo is compiled but not defined yet. to define it, run Chunk:



Loadstring is similar to LoadFile, but it does not read chunk from the file, but from a string;

Loadstring compilation does not care about the lexical scope:


In this example, G uses the local variable I as imagined, but F uses the global variable I; loadstring is always compiled in the global environment.







Difference between Lua dofile LoadFile loadstring

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.