首页 > 解决方案 > 如何使用函数更改全局变量?

问题描述

我试图画一个复选框,但我想让它成为一个功能

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

调用它我在函数中有一个全局变量作为“变量”,这样我就可以引用复选框的布尔值

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

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

标签: lua

解决方案


据此简单的数据类型在 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

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


推荐阅读