Page 1 of 1

Question about scope

Posted: Mon Apr 20, 2020 6:19 pm
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?

Re: Question about scope

Posted: Mon Apr 20, 2020 9:20 pm
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.

Re: Question about scope

Posted: Tue Apr 21, 2020 1:55 am
by DavitosanX
That really clears it up, thanks!