【问题标题】:(Lua) How do I increment a variable every time one of three if statements runs?(Lua)每次运行三个 if 语句之一时,如何增加一个变量?
【发布时间】:2020-05-10 13:00:37
【问题描述】:

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

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

【问题讨论】:

  • 为什么每次都把i设置回0
  • 哦,我明白了……那将是我正在寻找的语法问题。我认为它正在运行该功能,直到我停止模拟。但它实际上是在每次运行 if 语句之一时重新启动函数。感谢您的帮助。

标签: lua


【解决方案1】:

假设您有一个循环函数,例如 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

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

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2012-02-17
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多