首页 > 解决方案 > (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 的一些简单语法问题,我不知道也找不到如何正确修复。

如果这个小片段不足以回答这个问题,我很乐意提供更多代码。

标签: lua

解决方案


假设您有一个循环函数,例如sysCall_actuation每个模拟步骤正在执行的函数。正如 Joseph Sible-Reinstate Monica 所说,i每次执行模拟步骤时,您都将变量设置回零。为了实现您的目标,您必须在函数之外将变量设置为 0。有两种适当的方法可以实现这一目标:

  1. 在文件开头(或在定义使用变量的任何函数之前,例如在定义之前sysCall_actuation)在任何函数之外定义变量。
-- Beginning of the file.
local i = 0

..

function sysCall_actuation()
    ..
    i = i + 1
    ..
end
  1. 在函数中定义变量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

附带说明一下,尽可能练习使用局部变量,以保持内存清洁并避免出现模棱两可的变量。


推荐阅读