Page 1 of 1

Trying to reference specific value from {} object throws 'nil value' error

Posted: Wed Apr 24, 2019 1:49 pm
by dmf
Hi all,

I'm not sure if I have a syntax error or a lack of understanding here, but I've been puzzled about a bug that I haven't been able to fix for half an hour.

Here are the relevant code bits:

Code: Select all

link = {}
link.y = 1 
link.speed = 1
link.x = 1

function love.load()
    link = love.graphics.newImage("sprites/link solo.png")
end

function love.update(dt) 
    
    if love.keyboard.isDown('w') then 
    link.y = link.y - link.speed;                            [LINE WHERE ERROR OCCURS]
    end
    
end

function love.draw()
    love.graphics.draw(link, link.x, link.y)
end
Throws the following error:

Code: Select all

main.lua:21: attempt to perform arithmetic [b]on field 'y' (a nil value)[/b]


Traceback

main.lua:N: in function 'update'
[C]: in function 'xpcall'
Where am I going wrong?

Re: Trying to reference specific value from {} object throws 'nil value' error

Posted: Thu Apr 25, 2019 1:06 am
by MrFariator
The problem is with your love.load. You're effectively replacing the link table with an image, and as such the values you assigned at the top of your code do not exist anymore, causing the error.

What you probably meant to do is:

Code: Select all

function love.load()
    link.image = love.graphics.newImage("sprites/link solo.png") -- store the image under 'image' key in the table
end

function love.draw()
    love.graphics.draw(link.image, link.x, link.y) -- note the added .image
end

Re: Trying to reference specific value from {} object throws 'nil value' error

Posted: Thu Apr 25, 2019 7:22 am
by dmf
How could I possibly not have caught that?

Thanks so much!