lua - (Lua)每次运行三个 if 语句之一时,如何增加一个变量?
问题描述
我正在 CoppelliaSim 中为学校构建一个移动和感应机器人。CopelliaSim 使用 Lua 编写脚本。基本上每次机器人的前向传感器碰到什么东西时,三个 if 语句之一就会运行。我希望它计算这些 if 语句运行了多少次,一旦该计数达到一定数量(如 20),我将运行其他东西,它会做同样的事情(发现冲突,添加到计数,达到一个数量,然后切换回第一个)。
i=0
result=sim.readProximitySensor(noseSensor) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
result=sim.readProximitySensor(noseSensor0) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
result=sim.readProximitySensor(noseSensor1) -- Read the proximity sensor
-- If we detected something, we set the backward mode:
if (result>0) then backUntilTime=sim.getSimulationTime()+3
print("Collision Detected")
i=i+1
print(i)
end
上面是函数的开始,也是三个 If 语句之一。我打印只是为了看看它是否真的增加了。它正在打印,但没有增加(只是一遍又一遍)。这个机器人上有 3 个传感器(每个传感器都有一个 if 语句),它在第一次碰撞时将 i 加 1,并忽略其余的,即使它来自同一个传感器。我觉得我的问题只是 Lua 的一些简单语法问题,我不知道也找不到如何正确修复。
如果这个小片段不足以回答这个问题,我很乐意提供更多代码。
解决方案
假设您有一个循环函数,例如sysCall_actuation
每个模拟步骤正在执行的函数。正如 Joseph Sible-Reinstate Monica 所说,i
每次执行模拟步骤时,您都将变量设置回零。为了实现您的目标,您必须在函数之外将变量设置为 0。有两种适当的方法可以实现这一目标:
- 在文件开头(或在定义使用变量的任何函数之前,例如在定义之前
sysCall_actuation
)在任何函数之外定义变量。
-- Beginning of the file.
local i = 0
..
function sysCall_actuation()
..
i = i + 1
..
end
- 在函数中定义变量
sysCall_init
,这是 CoppeliaSim 中的适当方法。
function sysCall_init()
i = 0
..
end
最后,您可以在sysCall_actuation
函数中使用变量进行基本比较操作:
function sysCall_actuation()
..
if i > 20 then
i = 0 -- Reset 'i' so this function will not be running every step again and again.
-- Do something here.
..
end
附带说明一下,尽可能练习使用局部变量,以保持内存清洁并避免出现模棱两可的变量。
推荐阅读
- azure-iot-hub - Azure IoT Central 存储遥测数据多长时间?
- python - Bowyer-Watson 在尝试对无穷远处的顶点执行外接圆计算时不正确地进行三角测量
- javascript - 具有基于数组值的 3 向切换的 Vue 按钮
- jenkins-pipeline - Jenkins 与 jFrog Artifactory 推送 Docker 镜像
- python - pd.to_numeric() 列的 SettingWithCopyWarning
- python - 如何为强化学习环境显示 tkinter-canvas
- python - 用python绘制日期
- python-3.x - Tensorflow 对象检测 API - 验证丢失行为
- python-3.7 - 调试 asyncio 代码时,“poll 235.000 ms take 125.000 ms: 1 events”是什么意思?
- c# - 从不同的控件更新用户控件内容