Question about scope

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
DavitosanX
Prole
Posts: 2
Joined: Mon Apr 20, 2020 6:05 pm

Question about scope

Post by DavitosanX »

Hello! First time poster here. I've been interested in game development for some time, and I want to give LÖVE a try. I'm familiar with programming, mostly with Python and Javascript, but I'm new to Lua and LÖVE. I'm following Sheepolution's tutorial to get acquainted with the library, and after getting to the chapter about scope, I had an unexpected result. I tried the following:

Code: Select all

function love.load()
  text1 = "Hi!"
end

function love.draw()
  love.graphics.print(text1,400,300)
  love.graphics.print(text2,400,500)
end

function love.update(dt)
   text2 = "Something else"
end
I expected the program to crash, since text2 doesn't exist in the scope of love.draw(), but to my surprise, it runs fine, even if called before being declared. I tried the following:

Code: Select all

function love.load()
  text1 = "Hi!"
end

function something()
  text2 = "Something else"
end

function love.draw()
  love.graphics.print(text1,400,300)
  love.graphics.print(text2,400,500)
end

function love.update(dt)

end
which crashed as expected.

My question is: What's the difference between love.update() and something()? Why is the variable created within love.update() global, and can be used even before it's declared?
User avatar
zorg
Party member
Posts: 3465
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Question about scope

Post by zorg »

Hi and welcome to the forums!

The reason for the above behaviour is that Löve gives you a default love.run function that is responsible for calling love.load initially, as well as love.update and love.draw after, each frame, in that order.

The call order is what makes it work, because regardless of the order you defined the two callback functions, update will be called by love.run "first", hence text2 will exist by the time draw will be called.

In the second example, it would work the same if you called your something function in update as well, but you don't.

Also, technically, since lua variables are global by default, both text1 and text2 are global, and unless shadowed by some locals, are able to be referenced anywhere (after them being defined, i mean), you're just playing with their time of definition.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
DavitosanX
Prole
Posts: 2
Joined: Mon Apr 20, 2020 6:05 pm

Re: Question about scope

Post by DavitosanX »

That really clears it up, thanks!
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 2 guests