0

Im trying to draw a checkbox right but i want to make it a function

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

to call it I have a global variable as "variable" in the function so that I can reference the bool of the checkbox

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

but the issue is when i press on the checkbox it doesn't change the global

Jewls
  • 39
  • 5

3 Answers3

0

According to this, simple data types are passed in lua as values, not as references, so variable in local context is a copy of the global variable. Changing copy does not affect the original variable.


Tables are passed as references, though, so you can call:

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

where in the local scope having:

variable.testOne = not variable.testOne

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

Of course if this matches your case.

asikorski
  • 882
  • 6
  • 20
0

Lua is a pass-by-value language, so if you want to update something from the caller, you need to pass the table that it's in. In your case, that means changing function drawCheckBox(x, y, distance, title, variable) to function drawCheckBox(x, y, distance, title, tbl, key), changing all occurrences of variable in that function to tbl[key], and changing the call to the function from drawCheckBox(100, 100, 50, 'Test One', checkboxVars.testOne) to drawCheckBox(100, 100, 50, 'Test One', checkboxVars, 'testOne').

-1

If I understood your questions correctly, you want to pass a reference to the checkbox boolean to the function, then, whenever you click on it, the reference will be updated. However, Lua does not allow that (at least not for booleans).

Try reading those suggestions here.

You could also access the global variable directly from the _G table (the global table).

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