• Advertisement
Sign in to follow this  

How do variables and objects persist in Lua?

This topic is 1890 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Sorry if this is a confusing question.

Thanks.

Share this post


Link to post
Share on other sites
Advertisement
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 [b]chunk=loadfile(filename)[/b], then [b]chunk[/b] could later be executed as [b]chunk()[/b]. 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:

[code]
function foo()
local bar=4
end
[/code]

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. Edited by FLeBlanc

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement