Can't call table function as method is a nil value

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
Merkel
Prole
Posts: 2
Joined: Sun Oct 20, 2024 2:14 pm

Can't call table function as method is a nil value

Post by Merkel »

Hello
I am trying to implement a spawn function where enemies spawn at a specific rate which I am calling from the enemy.lua file to the main file. However, I keep on getting the error:
main.lua:55: attempt to call method 'spawn' (a nil value)
When I try to call the spawn function, I can't figure out why it returns a nil value. It functioned when the function was in the main.lua file but I wanted to make the code neater and have separate files for different game elements.

I have tried to look for similar problems on the forum but haven't found any that fix my problem. Below I have attached my enemy.lua and main.lua files so you can understand what might be causing the error.
enemy.lua
(1.93 KiB) Downloaded 109 times
main.lua
(8 KiB) Downloaded 89 times
User avatar
pgimeno
Party member
Posts: 3713
Joined: Sun Oct 18, 2015 2:58 pm

Re: Can't call table function as method is a nil value

Post by pgimeno »

I think the problem is in enemy.lua. In line 52, you're doing this:

Code: Select all

    return setmetatable({mapWidth = mapWidth, mapHeight = mapHeight}, enemies)
However, the enemies table does not have an `__index` metamethod. I can't check because you haven't provided enough code, but I think that inserting this line after line 2 will work:

Code: Select all

enemies.__index = enemies
Alternatively, you could change line 52 to do this instead:

Code: Select all

    return setmetatable({mapWidth = mapWidth, mapHeight = mapHeight}, {__index=enemies})
Merkel
Prole
Posts: 2
Joined: Sun Oct 20, 2024 2:14 pm

Re: Can't call table function as method is a nil value

Post by Merkel »

Thank you
This fixed my issue. I am new to Lua and Love so I was unaware I had to use the '__index' metamethod for the code to function. I appreciate the support
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 1 guest