Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for me to avoid using a global variable here?

Tags:

lua

love2d

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.

like image 507
Francisco Avatar asked Oct 15 '25 02:10

Francisco


2 Answers

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.

like image 192
lhf Avatar answered Oct 18 '25 06:10

lhf


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.

like image 20
Steven Avatar answered Oct 18 '25 05:10

Steven