So I just started learning Lua and Love2D and am using global variables when I need callback functions to communicate with eachother. For example:
enter_pressed = false
function love.update(dt)
if love.keyboard.isDown('return') then
enter_pressed = true
end
end
function love.draw()
if enter_pressed then
love.graphics.print("Enter has been pressed", 100, 200)
end
Is there any way to avoid having to write such code?
I haven't tried anything yet except for googling for possible solutions.
Just use a local variable:
local enter_pressed = false
If you want to limit its scope, make it local inside a do...end
block:
do
local enter_pressed = false
function love.update(dt)
...
end
function love.draw()
...
end
end
That's the way to define C-style static variables in Lua.
This is depending on the context, but technically, the update() and draw() methods work similair, so if you just want a quick result, you could also put the statement in the draw function:
function love.draw()
if love.keyboard.isDown('return') then
love.graphics.print("Enter has been pressed", 100, 200)
end
end
Otherwise, I'm also using global variables to let update() and draw() communicate with each other, though whether or not I use gobal variables for button presses depends on the context of the game.
Ex: if you want to use button presses to move an object, then you can put these actions in an object's update function, and then let the draw() only focus on drawing the said object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With