Although Lua is called an interpreted language, LUA does allow the source code to be precompiled into an intermediate form (analogy to Python's. PYc) before running the source code. The main feature of the differential interpretation language is whether the compiler is part of the language runtime library, that is, the ability to execute dynamically generated code (LUA can execute LUA code through Dofile).
In fact, the core function of Dofile is done by loadfile, so you can define Dofile:
LoadFile is not executing code, but simply compiling, returning a function that is executed by Dofile.
If you run a file more than once, you can call loadfile only once, repeating the function it returns.
Another function, loadstring, loads code from a string:
Copy Code code as follows:
> f = loadstring (' print ' hello ')
> f ()
Hello
Examine the execution domain of the LoadString code
Copy Code code as follows:
> i = 1
> f = loadstring (' i = i + 1 ')
> =i
1
--don't finish it. On the interactive command line, one line of code defaults to a block
> f = loadstring (' i=i+1 ')
> Do
>> Local I =1
>> F ()
>> Print (i)
>> End
1
> Do
>> Local i = 1
>> local F = loadstring (' i=i+1 ')
>> F ()
>> Print (i)
>> End
1
Two runs, I plus 1 in global.
So you can understand F:
Copy Code code as follows:
function f ()
i = i+1
End
But if you replace it directly, the result is inconsistent.
Copy Code code as follows:
> Do
>> Local I =1
>> function f ()
>> i = i + 1
>> End
>> F ()
>> Print (i)
>> End
2
It can be argued that loadstring compiled functions that are associated with global scope so that they do not exhibit closure characteristics, and therefore should not be used in this way!
In addition, if the syntax is incorrect, then LoadString returns nil.
You can use the Assert (LoadString (s)) () method.
If the parameter is not nil/false, return the argument, otherwise assert error;
A bit of loadfile and LoadString will know that Lua actually has a load function that receives a reader function and invokes its read code;