The function that completes the function is LoadFile. Unlike dofile, LoadFile only compiles the code into an intermediate code and returns the compiled chunk as a function. If an error occurs, nil and error message are returned. We can define dofile as follows: function dofile (filename) Local F = assert (LoadFile (filename) return F () End
You can use dofile (filename) If you only call it once. If you call it multiple times, you can use F = LoadFile (filename); F ()...
Loadstring is similar to LoadFile, except that it is read from a string.
In Lua, function definitions occur at runtime rather than during compilation.
F = loadstring ("I = I + 1") is equivalent to f = function () I = I + 1 end. However, loadstring does not care about the lexical range:
I = 33 local I = 0; F = loadstring ("I = I + 1") G = function () I = I + 1 endg uses the local variable I, F uses the global variable I, because f is always compiled in the global environment.
Mistakes are human nature, so we must handle errors in the best way. As an extension language, Lua is often embedded in other applications. When an error occurs, it cannot be a crash or exit statement. Print "enter a number :"
N = Io. Read ("* Number ")
If not n then error ("invalid input") End
The combination of if not condition then error end is so common that Lua has built a function specifically to do this. This function is assert.
Generally, when an exception occurs, you can either return an error code (NiL) or report an error ). There are no fixed guidelines for these two methods. However, we provide a general principle: errors should be reported for exceptions that are easy to avoid; otherwise, exceptions will be returned. Example: Math. Sin accepts radians of the number type. If the parameter is not a number, we should report an error instead of returning an error code. If we return an error code, we need to use it like this: Local res = math. sin (x) if not res then <error handling> in fact, we can easily detect this exception before calling sin: If not tonumber (X) then <error handling> generally, we do not detect the sin parameter or the return value of sin. If the parameter is not a number, it is often because the Code itself has a problem. In this case, stopping the execution and reporting an error is the simplest and most practical method.
On the contrary, Io. Open does not have a simple method to detect exceptions before calling open. Opening failed because the file does not exist or the permission is insufficient. By returning an error code, you can handle it in an appropriate way, such as asking the user to input another file name.
Lua compilation, execution, and debugging