Dofile reads the file to compile and executes, the function that really completes the function is loadfile; unlike Dofile, LoadFile simply compiles code into intermediate code and returns the compiled chunk as a function. Returns nil and error messages if an error occurs. So we can define Dofile:
Copy Code code as follows:
function dofile (filename)
Local F = assert (LoadFile (filename))
return F ()
End
If you only call once, you can use Dofile (filename), if it is called multiple times, you can f = loadfile (filename); f (); F () ...
LoadString is similar to loadfile, except that he reads it from a string.
In Lua, function definitions occur at runtime, not at compile time.
Copy Code code as follows:
f = loadstring ("i=i+1")
is equivalent to the F = function () i = I+1 end. But LoadString doesn't care about lexical scopes:
i = 33
Local i = 0;
f = loadstring ("i=i+1")
g = function () i = I+1 End
G uses the local variable I, and F uses the global variable I, because F is always compiled in the global environment.
It is human nature to err, so we must deal with mistakes in the best way. Lua, as an extended language, is often embedded in other applications, and when errors occur, it is not easy to crash or exit.
Copy Code code as follows:
Print "Enter a number:"
n = io.read ("*number")
If not n then error (' Invalid input ') end
If not condition then the combination of the error end is so common that LUA specifically constructs a function to do this, and this function is assert.
Typically, when an exception occurs, you have two ways to handle it, either by returning the error code (nil) or by the Fault (error). There are no fixed criteria for choosing between these two approaches. But we offer common principles: exceptions that are easy to avoid should be error-prone, or return an exception. An example is provided:
Math.sin accept the Radian value of the number type, and if the parameter is not number, we should do an error instead of returning the wrong code. Assuming that we are returning the error code, then we have to use this:
Copy Code code as follows:
Local res = Math.sin (x)
If not res then
<error handling>
In fact, we can easily detect this anomaly before calling sin:
Copy Code code as follows:
If not Tonumber (x) Then
<error handling>
In general, we do not detect the arguments of sin, nor do we detect the return value of sin. If the argument is not number, it is often the case that our code itself is wrong. In this case, stopping execution and error is the simplest and most practical way to do it.
Conversely, io.open this function, there is no simple way to detect an exception before calling open. Open failure may be due to a file that does not exist or insufficient permissions. By returning the error code, you can handle it in the appropriate way, such as letting the user enter another file name.