Lua函数作用域
所以我有一个希望很简单的问题,但我不明白为什么我的代码没有做我想要的事情。
function Sound:load()
trackToPlay = musicDownbeat
trackToPlay:play()
end
function Sound:changeMusic()
if trackToPlay == musicUpbeat then
trackToPlay:stop()
trackToPlay = musicDownbeat
trackToPlay:play()
end
if trackToPlay == musicDownbeat then
trackToPlay:stop()
trackToPlay = musicUpbeat
trackToPlay:play()
end
end
所以我有两个可以在 musicUpbeat 和 musicDownbeat 之间交替的源轨道,并且在代码中的这一点(我已经剥离了 Sound:load() 以使其尽可能清晰),每次 changeMusic() 是调用时,trackToPlay 始终为musicDownbeat,这意味着每次调用changeMusic() 时,音乐都会停止并更改为musicUpbeat。
Sound:load() 只被调用一次,对吗?那么为什么我的 trackToPlay 更改没有被保存呢?
So I've got a hopefully easy question, but I don't understand why my code isn't doing what I want it to.
function Sound:load()
trackToPlay = musicDownbeat
trackToPlay:play()
end
function Sound:changeMusic()
if trackToPlay == musicUpbeat then
trackToPlay:stop()
trackToPlay = musicDownbeat
trackToPlay:play()
end
if trackToPlay == musicDownbeat then
trackToPlay:stop()
trackToPlay = musicUpbeat
trackToPlay:play()
end
end
So I've got two Source tracks that can be alternated between, musicUpbeat and musicDownbeat, and at this point in the code (I have stripped down Sound:load() to make it as clear as possible), every time changeMusic() is called, trackToPlay is always musicDownbeat, meaning that every time changeMusic() is called, the music stops and is changed to musicUpbeat.
Sound:load() is only called once, right? So why are my trackToPlay changes not being saved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在函数
changeMusic
中。您需要使用elseif
而不是两个if
语句。您的代码应如下所示:如果
trackToPlay
为musicUpbeat
(它将在changeMusic
之后),则您在原始代码中编写的方式第一次调用),会被第一个语句改变为musicDownbeat
,然后立即被第二个if
语句改变为musicUpbeat
。The problem is in the function
changeMusic
. You need to useelseif
instead of twoif
statements. Your code should look like this:The way you have written it in your original code, if
trackToPlay
ismusicUpbeat
(it will be afterchangeMusic
is called the first time), it will be changed intomusicDownbeat
by the first statement, and then immediately changed intomusicUpbeat
by the secondif
statement.