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

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
dmf
Prole
Posts: 2
Joined: Wed Apr 24, 2019 1:27 pm

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

Post 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?
MrFariator
Party member
Posts: 512
Joined: Wed Oct 05, 2016 11:53 am

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

Post 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
dmf
Prole
Posts: 2
Joined: Wed Apr 24, 2019 1:27 pm

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

Post by dmf »

How could I possibly not have caught that?

Thanks so much!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 135 guests