4

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.

Francisco
  • 41
  • 1

3 Answers3

2

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    This would often be done without the `do`-`end` block if there's no need to limit the scope. – Luatic May 24 '23 at 10:11
  • 1
    it's functionally equivalent to a global variable – user253751 May 24 '23 at 10:11
  • 1
    @Luatic, I've edited my answer to include your comment Thanks for the nudge. – lhf May 24 '23 at 10:17
  • 1
    @user253751 But technically different, as `local` scopes the variable to the *chunk*, effectively file scope. Without it, you pollute `_G` (in Lua 5.1). – Oka May 24 '23 at 23:10
1

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.

Steven
  • 1,996
  • 3
  • 22
  • 33
0

Even love can be local in LÖVE
Just try it...

-- main.lua
local enter_pressed = false
local love = require('love')

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
end

PS: LÖVE created Objects often has UserData where you can store such Data if you like
See for Example: https://love2d.org/wiki/Body:setUserData
PPS: Also and not even for Beginners it is worth a look on...
https://love2d.org/wiki/Config_Files
...and use it ;-)

koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15