尝试对全局变量 'front' 进行索引(但它的值为 nil)。

我正在使用 Corona SDK 编写 Lua 代码,遇到了错误 "Attempt to index global 'front' (a nil value)",在第75行

我正在 game.lua 中进行此操作,从 main.lua 重定向过来(这部分工作正常)。链接是 pastebin,因为在 stackoverflow 上混淆了代码!

点赞
用户1271435
用户1271435

最可能是因为变量未能初始化。

local front = display.newImage("front1.png")

确保图像文件位于与“game.lua”相同的目录中,并且文件名拼写正确。

2013-08-31 14:00:41
用户185316
用户185316

你需要在createScene()函数中为你的变量添加前向声明,使它们可以在enterScene()函数中使用。并且,在destroyScene()函数中一定要移除所有的事件监听器。

例如:

-- 在这里使用前向声明,让 `front` 在模块中的作用域中
local front

function scene:createScene(event)
    -- ...
    -- 不要在这里使用 `local`,因为 `front` 已经被定义了
    front = display.newImage("front1.png")
    front.y=470
    front.speed = 4
    front:setReferencePoint(display.BottomLeftReferencePoint)
    -- ...
end

function scene:enterScene(event)
    -- ...
    -- 由于 `front` 在父作用域中,
    -- 我们可以在这里访问它
    Runtime:addEventListener("enterFrame", front)
    -- ...
end

function scene:destroyScene(event)
    -- 在这里一定要移除你的监听器
    Runtime:removeEventListener("enterFrame", front)
end
2013-09-02 11:17:03