试图在Lua中随机选择

Cin*_*ere 2 random lua function

这是我到目前为止所拥有的,但似乎每当我尝试运行它时,它就会关闭.

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
Run Code Online (Sandbox Code Playgroud)

这是完整的背景.

小智 8

这个代码存在一些问题,第一个问题(正如Lorenzo Donati所指出的那样)是你已经将实际的调用包装在里面random(),给你一块从未真正做过任何事情的东西(woops).

第二个是你要调用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)
Run Code Online (Sandbox Code Playgroud)

而且只是为了踢,我们可以用条件值替换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)
Run Code Online (Sandbox Code Playgroud)