The size this frame large enough hold the functions local data
580 10. BASIC VM DESIGN AND IMPLEMENTATION
function.
We now have all the information we need to safely call a function, so let’s review. When calling a function:
Returning From a Function
The explanation of how a function is called overlapped pretty heavily with how a function returns, so this will be quick. To return from a function, the top of the stack is popped off. This element contains both the index of the function we’re returning from, as well as the location of the previous stack frame. The first of these two pieces of information is used to retrieve the cur-rent function’s Func structure from the function table.
Figure 10.13
Locating the return
Like all good programs, your VM has to play nice with its operating environment and properly clean up after itself. A script can terminate for a number of reasons, ranging from the last instruc-tion being reached to the game engine sending a specific request to shut down. In both cases, major structures like the instruction stream, stack, and all global data tables must be freed. This of course is one of the easier phases of the VM’s lifecycle, but it’s extremely important.
Remember that a real-world game may load, run, and terminate thousands of scripts as it pro-gresses, which means you can easily clog up the system’s resources if each one of these aren’t properly removed.