I am using LuaBind to embed Lua scripting into my C++ game engine. My question is how do variables persist in this situation. For example, a game object has the name of a Lua file associated with it. At the creation of the Game object in C++, I call the "OnCreate()" function in the lua script associated with the game object. It seems like I should tell lua what Lua file to look at, and then run the function for that specific file. What if last time I had that specific file open, I set a variable local to the whole script. When the file is reopened, does lua automatically know, and give me access to those variables again?
When a Lua file is executed (using dofile, pcall, or whatever) it is loaded, compiled to Lua code and executed as a "chunk". Think of a "chunk" like an anonymous function. In fact, if you do something in Lua script like chunk=loadfile(filename), then chunk could later be executed as chunk(). So in a way, you can think of a Lua file as a function.
Now, when you declare a variable local, it is only alive during the execution of that function. Say you have this function:
The only time bar is valid is when foo is executing. Before foo executes, bar doesn't exist. After foo exits, bar is marked for garbage collection. Similarly, any variable declared local to a Lua file is only valid when the compiled chunk loaded from that file is actually executing. Once it is no longer executing, any locals will be garbage collected.
If you want a value to be persistent across multiple calls to the chunk, it has to exist outside of the local scope of the chunk.