luaruntime-errorgame-developmentlove2d

Lua Love2d Error, : attempt to call method a nil value


I am working on a simple game with love2d. The game have 3 states : Play, menu and ended. In the ended part, I wrote some button for the player to return to menu and restart the game. However I got the error : attempt to call method "checkPressed" (a nil value)

Here is the ended state's script:

local love = require("love")
local button = require "button/button"
local score = ""
local maxScore = ""

local buttons = {}

m = {}

function m:enter(_score, _maxScore)

    love.graphics.setLineWidth(6)

    table.insert(buttons, button(380, 500, "Restart", 200, 90))

    score = "Score: " .. _score
    maxScore = "MaxScore: " .. _maxScore
    
end

function m:update(dt)

    for i = 1, #buttons do
        
        buttons[i]:checkPressed(dt) ------ Error Here -----------

    end

end

And here is the button's script:

local isPressed = require "button/isPressed"
m = {}

function init(_x, _y, _text, _width, _height)
    
    m.x = _x
    m.y = _y

    m.width = _width
    m.height = _height

    m.text = _text
    m._isPressed = false

    m.waitTimer = 0

    return m

end

function m:checkPressed(dt)

    if isPressed(self.x, self.y, self.width, self.height) then
        self._isPressed = true
    end

    if self._isPressed == true then
        
        self.waitTimer = self.waitTimer + 3 * dt

    end
    
end



return init

At the next moment, I solve the problem, but I don't know why it works. Script I changed:

local isPressed = require "button/isPressed"
m = {}

function init(_x, _y, _text, _width, _height)
    
    m.x = _x
    m.y = _y

    m.width = _width
    m.height = _height

    m.text = _text
    m._isPressed = false

    m.waitTimer = 0

    m.checkPressed = function (self, dt) ------- Changed Here --------

        if isPressed(self.x, self.y, self.width, self.height) then
            self._isPressed = true
        end
    
        if self._isPressed == true then
            
            self.waitTimer = self.waitTimer + 3 * dt
    
        end
        
        
    end

    return m

end

return init

If you have an idea why, please tell me. Thank you.


Solution

  • You have initialized global variable m twice, the second initialization has erased everything (including checkPressed) added previously to m.
    Solution: replace both statements m = {} with m = m or {} to preserve data already inserted in m.
    Or just remove m = {} from the main script as m is created inside button script.