如何通过函数改变全局变量?

我正在尝试正确地绘制一个复选框,但我想将其作为函数。

function drawCheckBox(x, y, distance, title, variable)

local mousePos = input:get_mouse_pos()
local checkBoxColor

local checkSize = 15;

if (mousePos.x > x and mousePos.x < x + checkSize) and (mousePos.y > y and mousePos.y < y + checkSize)  then
    if input:is_key_down( 0x1 ) then
        variable = not variable
    end
end

if variable == true then
    checkBoxColor = colors.white
else
    checkBoxColor = colors.red
end

render:rect_filled( x, y, checkSize, checkSize, checkBoxColor)
render:text( font, x + distance, y, title, colors.white )

end

调用此函数时,我在函数中有一个全局变量作为"variable",以便我可以引用复选框的布尔值

drawCheckBox(100, 100, 50, 'Test One', checkboxVars.testOne)

但问题是当我按下复选框时它不能改变全局变量。

点赞
用户11501222
用户11501222

根据 这里,简单数据类型在 lua 中作为值而不是引用传递,所以本地上下文中的 variable 是全局变量的 副本。更改副本不会影响原始变量。


表格则作为引用传递,因此您可以调用:

drawCheckBox(100, 100, 50, 'Test One', checkboxVars)

在本地作用域中具有以下内容:

variable.testOne = not variable.testOne
if variable.testOne == true then
    checkBoxColor = colors.white
else
    checkBoxColor = colors.red
end

当然,如果这符合您的情况。

2020-05-18 09:27:46
用户2725326
用户2725326

如果我正确理解了你的问题,你想将一个 checkbox 布尔值的引用传递给函数,然后每当你点击它时,引用就会更新。然而,Lua 不允许这样做(至少对于布尔值不行)。

请尝试阅读这里的建议

你也可以直接从 _G 表(全局表)访问全局变量。

function drawCheckBox(x, y, distance, title, globalVariableName)

local mousePos = input:get_mouse_pos()
local checkBoxColor

local checkSize = 15;

if (mousePos.x > x and mousePos.x < x + checkSize) and (mousePos.y > y and mousePos.y < y + checkSize)  then
    if input:is_key_down( 0x1 ) then
        _G("globalVariableName") = not _G("globalVariableName")
    end
end

if _G("globalVariableName") == true then
    checkBoxColor = colors.white
else
    checkBoxColor = colors.red
end

render:rect_filled( x, y, checkSize, checkSize, checkBoxColor)
render:text( font, x + distance, y, title, colors.white )

end
2020-05-18 12:56:42
用户7509065
用户7509065

Lua 是一种传值语言,因此如果您想从调用方更新某个内容,您需要传递该内容所在的表。在您的情况下,这意味着将 function drawCheckBox(x, y, distance, title, variable) 改为 function drawCheckBox(x, y, distance, title, tbl, key),在该函数中将所有出现的 variable 改为 tbl[key],并将函数调用从 drawCheckBox(100, 100, 50, 'Test One', checkboxVars.testOne) 改为 drawCheckBox(100, 100, 50, 'Test One', checkboxVars, 'testOne')

2020-05-18 14:46:33