lua - 如何使用函数更改全局变量?
问题描述
我试图画一个复选框,但我想让它成为一个功能
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 中作为值传递,而不是作为引用,因此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
当然,如果这符合您的情况。
推荐阅读
- android - React Native 在物理 Android 设备中不起作用
- powershell - 如何从 powershell 脚本中使用 SQL 中的变量
- scala - 如何在 Scala 中加入 Spark 数据帧列表?
- c# - 在调用 .ReleaseMutex() 之前,线程可以多次调用 Mutex 的 .WaitOne() 吗?反之亦然?
- java - java.lang.NoSuchMethodError: io.netty.buffer.PooledByteBufAllocator.metric()Lio/netty/buffer/PooledByteBufAllocatorMetric;
- powershell - 将脚本结果导出为 CSV
- jquery - 如何检测触摸或点击?
- vba - 使用 VBA 在 Powerpoint 数组中加载数据
- sql - 使用登录添加复制日志读取器代理时出错
- model - 从 RethinkDB 获取数据