Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


How do variables and objects persist in Lua?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 Kurasu1415   Members   -  Reputation: 170

Like
0Likes
Like

Posted 14 November 2012 - 03:02 PM

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.

Sponsor:

#2 FLeBlanc   Crossbones+   -  Reputation: 3109

Like
0Likes
Like

Posted 14 November 2012 - 04:50 PM

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:

function foo()
     local bar=4
end

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, 14 November 2012 - 04:50 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS