Search code examples
lualove2d

Love2D Lua error: attempt to call field 'isDown' (a nil value)


This is my code in Love2D:

function love.load()   
    ninja = love.graphics.newImage("Ninja.png")
    x = 0
    y = 0
    speed = 256
end

function love.update(dt)
    if love.keyboard.isDown("right") then
        ninja = love.graphics.newImage("NinjaRight.png")
        x = x + (speed * dt)
    end

    if love.keyboard.isDown("left") then
        ninja = love.graphics.newImage("NinjaLeft.png")
        x = x - (speed * dt)
    end

    if love.keyboard.isDown("down") then
        y = y + (speed * dt)
    end

    if love.keyboard.isDown("up") then
        y = y - (speed * dt)
    end

    if love.joystick.isDown(joystick, 1, 2, 3, 4) then
        a = 5
    end
end


function love.draw()
    love.graphics.draw(ninja, x, y)
end

I want to make the game to recognize a controller when connected. But when I run the game, I receive the error:

attempt to call field 'isDown'(a nil value)

Where is the problem?


Solution

  • Since LÖVE 0.9.0 Joystick related isDown() function is moved to another namespace/table/You name ir or more "object" like structure. [1]

    So, in Your code You should use it something like this:

    --Get table of all connected Joysticks:
    local joysticks = love.joystick.getJoysticks()
    
    --Pick first one:
    local joystick = joysticks[1]
    
    if joystick:isDown(1, 2, 3, 4) then
        a = 5
    end
    

    Where joystick is Your Joystick object. [2]

    Be aware, love.keyboard.isDown() usage haven't changed yet. But, I guess, it's about to too. Sooner or later.

    [1] https://love2d.org/wiki/Joystick:isDown

    [2] https://love2d.org/wiki/love.joystick.getJoysticks