【问题标题】:Attempting to make a random choice in Lua尝试在 Lua 中进行随机选择
【发布时间】:2013-08-27 02:09:42
【问题描述】:

这是我目前所拥有的,但似乎每次我尝试运行它时,它都会关闭。

function wait(seconds)
  local start = os.time()
  repeat until os.time() > start + seconds
  end

function random(chance)
  if math.random() <= chance then
  print ("yes")
  elseif math.random() > chance then
  print ("no")
  end

random(0.5)
wait(5)
end

这是完整的上下文。

【问题讨论】:

  • 请格式化您的代码,使其清晰易读。

标签: function random lua


【解决方案1】:

该代码存在一些问题,第一个问题(正如 Lorenzo Donati 指出的那样)是您将实际调用包装在 random() 中,从而为您提供了一个实际上从不做任何事情的块(哎呀)。

第二个是你调用math.random() 两次,给你两个不同的值;这意味着两种测试都完全有可能不成立。

第三个是次要的:您正在为非此即彼的选择进行两次测试;第一个测试会告诉我们我们需要知道的一切:

function wait(seconds)
    local start = os.time()
    repeat until os.time() > start + seconds
end

function random(chance)
    local r = math.random()
    if r <= chance then
        print ("yes")
    else
        print ("no")
    end
end

random(0.5)
wait(5)

只是为了好玩,我们可以用条件值替换 if 块,因此:

function wait(seconds)
    local start = os.time()
    repeat until os.time() > start + seconds
end

function random(chance)
    local r = math.random()
    print(r<=chance and "yes" or "no")
end

random(0.5)
wait(5)

【讨论】:

    【解决方案2】:

    可能你打算写这个:

    function wait(seconds)
      local start = os.time()
      repeat until os.time() > start + seconds
    end
    
    function random(chance)
        if math.random() <= chance then
            print ("yes")
        elseif math.random() > chance then
            print ("no")
        end
    end
    
    random(0.5)
    wait(5)
    

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 2021-10-08
      • 1970-01-01
      • 2011-05-06
      • 2017-01-03
      • 2010-11-19
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      相关资源
      最近更新 更多