尝试在Lua中进行随机选择

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

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

这是完整的上下文。

点赞
用户2633423
用户2633423

也许你想要写这个代码:

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)
2013-08-23 22:34:08
用户2712809
用户2712809

有一些问题与那段代码有关,第一(正如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-block,这样:

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)
2013-08-24 03:17:17