Why does it give me a 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
Seth144k
Prole
Posts: 29
Joined: Wed Jan 19, 2022 8:45 pm

Why does it give me a nil value error

Post by Seth144k »

Hi ive been working on collisions for a game idea i had and i have it inside of collision.lua and it doesnt seem to work at all. Ive tried moving the collisions outside of the function and it doesnt seem like it wants to work. instead i get this error when i start the game: Error

src/util/collision.lua:5: attempt to index global 'collision' (a nil value)


Traceback

[love "callbacks.lua"]:228: in function 'handler'
src/util/collision.lua:5: in main chunk
[C]: in function 'require'
main.lua:3: in main chunk
[C]: in function 'require'
[C]: in function 'xpcall'
[C]: in function 'xpcall'

can anyone please tell me the issue please thank you! also here is my .love
Attachments
coin game.love
(2.8 KiB) Downloaded 64 times
MrFariator
Party member
Posts: 509
Joined: Wed Oct 05, 2016 11:53 am

Re: Why does it give me a nil value error

Post by MrFariator »

As the error states, you are trying to index a global that doesn't exist. You'll have to define the table that's being used, like the following:

Code: Select all

require("src.util.AABB")
require("src.generation")
require("src.player")
collision = {} -- define the collision table

-- now you can add a function to it
function collision:update(dt)
    if self.y <= 0 then
        self.y = 0
    end
end
However, because you're trying to treat this like a module or library, I'd recommend setting the collision table into a local, and return it at the end of the file:

Code: Select all

local collision = {} -- now a local to this file
function collision:update(dt)
    -- ...stuff goes here
end
return collision -- when other files call require(), they will receive a reference to the 'collision' table

--eq. in player.lua, you could do
local collision = require("src.util.collision")
This is because "collision" is a very vague name for a global variable, that might accidentally get overridden elsewhere. For advice on how to write lua modules, kikito has some pretty snappy tips here.
User avatar
GVovkiv
Party member
Posts: 668
Joined: Fri Jan 15, 2021 7:29 am

Re: Why does it give me a nil value error

Post by GVovkiv »

MrFariator wrote: Wed May 18, 2022 3:25 pm here.
Uh, kikito's guide of writing modules in lua.
Good read.
Maybe it worth place it somewhere on title page of wiki?
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Amazon [Bot] and 50 guests