函数内变量(Corona Lua)

我已经在任何地方搜索如何在函数内更改变量的答案。我尝试了许多不同的解决方案,但到目前为止没有一个有效。

我的计划是在按下按钮时运行的函数内更改名为“stateRed”的变量。运行函数时,变量将更改为“READY”。然后我将使用此变量运行单独的代码块(实际游戏)。这里有两个这样的按钮。

我的代码看起来像这样:

function ReadyRed()
stateRed = 'READY'
stateBtnRed = widget.newButton
{
    defaultFile = "ready_red.png",
    overFile = "unready_red.png",
    label = "Ready",
    emboss = true,
    onPress = unreadyStateRed,
}
stateBtnRed.rotation = 90; stateBtnRed.width = 90; stateBtnRed.height = 90; stateBtnRed.x = display.contentWidth / 2 - 170; stateBtnRed.y = display.contentHeight - 270
return stateRed
end

function UnreadyRed()
local stateRed = 'UNREADY'
stateBtnRed = widget.newButton
{
    defaultFile = "unready_red.png",
    overFile = "ready_red.png",
    label = "Unready",
    emboss = true,
    onPress = readyStateRed,
}
stateBtnRed.rotation = 90; stateBtnRed.width = 90; stateBtnRed.height = 90; stateBtnRed.x = display.contentWidth / 2 - 170; stateBtnRed.y = display.contentHeight - 270
return stateRed
end

启动游戏的代码如下:

if stateRed == 'READY' and stateBlue == 'Ready' then
点赞
用户7026995
用户7026995

如果变量 stateRed 是全局的,则需要移除变量名前的 local 声明,例如:

function UnreadyRed()
    stateRed = 'UNREADY'
    ...
end

注意:

  • ReadyRedUnreadyRed 函数中,你可能不需要返回 stateRed,因为它是全局变量。
  • 使用一种命名规范。建议你使用驼峰命名法
2018-11-17 10:55:23