【问题标题】:Lua Function ScopeLua 函数作用域
【发布时间】:2012-03-07 12:55:36
【问题描述】:

所以我有一个希望很简单的问题,但我不明白为什么我的代码没有按照我的意愿去做。

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之间交替的Source轨道,并且在代码的这一点上(我已经剥离了Sound:load()以使其尽可能清晰),每次changeMusic () 被调用,trackToPlay 始终是musicDownbeat,意思是每次调用changeMusic() 时,音乐停止并变为musicUpbeat。

Sound:load() 只被调用一次,对吧?那么为什么我的 trackToPlay 更改没有保存?

【问题讨论】:

  • "Sound:load() 只被调用一次,对吧?"我不知道;这是你的功能,对吧?你多久打电话一次?或者这是一个专门的 Lua 环境?
  • 我也在使用 Love2D 框架,对不起,我应该把它包括在内,虽然我不知道这是否与问题有关。目前,每次按“f”键时都会调用该函数。

标签: function scope lua love2d


【解决方案1】:

问题在于函数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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2021-03-10
    • 2017-01-15
    • 2017-05-26
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多