Page 1 of 1

Why does it give me a nil value error

Posted: Wed May 18, 2022 1:56 pm
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

Re: Why does it give me a nil value error

Posted: Wed May 18, 2022 3:25 pm
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.

Re: Why does it give me a nil value error

Posted: Wed May 18, 2022 3:45 pm
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?