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