【问题标题】:Variables inside Functions (Corona Lua)函数内部的变量(Corona Lua)
【发布时间】:2018-11-17 18:55:23
【问题描述】:

我到处寻找有关如何更改函数内部变量的答案。我尝试了许多不同的解决方案,但到目前为止都没有奏效。

我的计划是在按下按钮时运行的函数中更改名为“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

【问题讨论】:

  • stateRed 是全局变量还是局部变量?
  • 在您的代码中,您定义了两个不同的变量,名称相同 stateRed。一是全局,二是局部(只存在于UnreadyRed函数中)。
  • stateRed 是一个全局变量

标签: lua coronasdk


【解决方案1】:

如果变量 stateRed 是全局变量,则删除变量名称之前的 local 关键字,即

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

注意:

  • 您可能不需要在ReadyRedUnreadyRed 函数中返回stateRed,因为stateRed 是全局变量。
  • 使用一种符号样式。我推荐你Camel Case notation

【讨论】:

    猜你喜欢
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2017-02-02
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多