【问题标题】:Attempt to index global 'rectangle' (a nil value) Error尝试索引全局“矩形”(零值)错误
【发布时间】:2013-09-16 11:17:00
【问题描述】:

我是 Corona 的新手,我正在尝试按照本教程使用触摸在屏幕上拖动对象。

http://thatssopanda.com/corona-sdk-tutorials/dragging-an-object-in-corona-sdk/

我使用了几乎完全相同的代码,只是我的变量名称不同,并且是矩形而不是圆形,但我不断收到上述错误。

有什么想法吗?错误:

(文件:/Users/paulbyrne/Desktop/Transition/main.lua 行:6

尝试索引全局“矩形”(零值)

堆栈回溯: [C]: ? /Users/paulbyrne/Desktop/Transition/main.lua:6: 在主块中)

    local rectangleShape = display.newRect( 100, 100, 100, 100 )
    rectangleShape:setFillColor( 255, 255, 255 )

    function rectangle:touch( event)
        if event.phase == "began" then
            display.getCurrentStage():setFocus( self, event.id)
            self.isFocus = true

            self.markX = self.x
            self.markY = self.y

        elseif self.isFocus then

            if event.phase == "moved" then
                self.x = event.x - event.xStart + self.markX
                self.y = event.y - event.yStart + self.markX
            elseif event.phase == "ended" or event.phase == "cancelled" then
                display.getCurrentStage():setFocus( self, nil )
                self.isFocus = false
            end

        end 

        return true
    end
    rectangleShape:addEventListener( "touch", rectangle )   

【问题讨论】:

    标签: lua coronasdk


    【解决方案1】:

    你写的相当于:

    rectangle.touch = function (self, event)
        ...
    end
    

    如果 rectangle 为 nil,那么这将失败,因为您实际上是在索引 nil。 就我个人而言,我更喜欢避免使用 ':' 编写函数定义,因为它会掩盖您正在有效执行的操作以及输入参数(隐藏的 self)。

    【讨论】:

    • 谢谢,我刚刚意识到函数 rectangle:touch ... 不是声明一个名为 rectangle 的函数,而是引用矩形对象。我同意用手写的方式写出更清楚。非常感谢。
    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 2020-11-03
    • 2015-04-09
    • 2014-01-26
    • 2013-06-07
    • 2020-03-08
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多