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更改未被保存?

原文链接 https://stackoverflow.com/questions/9305986

点赞
stackoverflow用户221509
stackoverflow用户221509

问题出在函数 changeMusic 中。你需要使用 elseif 代替两个 if 语句。你的代码应该像这样:

function Sound:changeMusic()
 if trackToPlay == musicUpbeat then
      trackToPlay:stop()
      trackToPlay = musicDownbeat
      trackToPlay:play()
 elseif trackToPlay == musicDownbeat then
      trackToPlay:stop()
      trackToPlay = musicUpbeat
      trackToPlay:play()
 end
end

在你原本的代码中,如果 trackToPlaymusicUpbeat(在第一次调用 changeMusic 后就会变成这样),它会被第一个语句改为 musicDownbeat,然后立即被第二个 if 语句改回 musicUpbeat

2012-02-16 08:28:15