简体   繁体   English

Lua Love2d 错误,:尝试调用一个 nil 值的方法

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

I am working on a simple game with love2d.我正在用 love2d 开发一个简单的游戏。 The game have 3 states: Play, menu and ended.游戏有 3 种状态:播放、菜单和结束。 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)但是我得到了错误:尝试调用方法“checkPressed”(一个零值)

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.谢谢你。

You have initialized global variable m twice, the second initialization has erased everything (including checkPressed ) added previously to m .您已经初始化全局变量m两次,第二次初始化删除了之前添加到m的所有内容(包括checkPressed )。
Solution: replace both statements m = {} with m = m or {} to preserve data already inserted in m .解决方案:将m = {}两个语句替换为m = m or {}以保留已插入m中的数据。
Or just remove m = {} from the main script as m is created inside button script.或者只需从主脚本中删除m = {} ,因为m是在按钮脚本中创建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM