问题描述
在此程序中,当您点击对象 moon 时,功能 changeScene()会将场景从 end.lua 更改为 start.lua (以重新启动游戏)。
但是在 start.lua 中,月亮仍显示在屏幕上。
因此,在 changeScene()中,我添加了display.remove( moon )
,但它不起作用。
我也尝试过moon:removeSelf()
和sceneGroup:remove(3)
。
此外,我不知道为什么moon:removeSelf()
会出现此错误:
ERROR: Runtime error <br />
end.lua:13: attempt to index global 'moon' (a nil value) <br />
stack traceback: <br />
end.lua:13: in function '?' <br />
?: in function <?:190>
我在做什么错? (欢迎提供有关代码的其他建议)
end.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- create()
function scene:create( event )
local sceneGroup = self.view
local function changeScene()
--moon:removeSelf()
--sceneGroup:remove(3)
display.remove( moon )
--moon = nil
composer.removeScene("end")
composer.gotoScene( "start",{effect = "slideUp",time = 500} )
end
local text = display.newText(correctAnswers .. "/10 correct ",display.contentCenterX,280,native.systemFont,50)
text.y = display.contentCenterY-100
sceneGroup:insert(text)
local text2 = display.newText("Press the moon to RESTART ",20)
text2.x = display.contentCenterX
text2.y = display.contentCenterY+200
transition.blink( text2,{ time=2500 } )
sceneGroup:insert(text2)
local floor = display.newImageRect( "floor.png",300,50 )
floor.x = display.contentCenterX
floor.y = display.viewableContentHeight+100
local moon = display.newImageRect( "balloon.png",112,112 )
moon.x = math.random( 40,display.contentWidth-40 )
moon.y = 50
moon.alpha = 0.8
local physics = require( "physics" )
physics.start()
physics.addBody( floor,"static" )
physics.addBody( moon,"dynamic",{ radius=50,bounce=0.5 } )
moon:addEventListener( "tap",changeScene )
end
解决方法
可以在函数内部使用局部变量。 But variables can only be used when they are in scope。
当然,函数定义的参数列表中的变量在函数内部。但是,也可以使用参数列表中不是符号的变量,只要它们在函数定义时在范围内即可。在OP代码中,changeScene
函数没有参数,因此在函数定义时,函数中使用的任何变量都必须在范围内。变量moon
是一个局部变量,它在声明该变量的块的范围内,在定义点之后 。因此,在定义moon
时,changeScene
的作用范围不是 。解决此问题的一种方法是将moon
的定义移到changeScene
的定义之前的点:
local moon = display.newImageRect("balloon.png",112,112)
moon.x = math.random(40,display.contentWidth - 40)
moon.y = 50
moon.alpha = 0.8
local function changeScene ()
display.remove(moon)
composer.removeScene("end")
composer.gotoScene("start",{effect = "slideUp",time = 500})
end
,
在Lua中,当我们使用一个函数时,无论何时我们要在其中调用变量,它都必须是local
,但是当我们在一个函数中调用它之外的变量时,它必须是{ {1}}。
删除global
变量声明中的local
,看看是否可以解决问题