Function 尝试在Lua中进行随机选择

Function 尝试在Lua中进行随机选择,function,random,lua,Function,Random,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 the

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

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
功能等待(秒)
本地启动=os.time()
重复此操作,直到os.time()>开始+秒
结束
随机函数(机会)
如果math.random()偶然
打印(“否”)
结束
随机(0.5)
等等(5)
结束

这是完整的上下文。

您可能想写以下内容:

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)
功能等待(秒)
本地启动=os.time()
重复此操作,直到os.time()>开始+秒
结束
随机函数(机会)
如果math.random()偶然
打印(“否”)
结束
结束
随机(0.5)
等等(5)

该代码存在一些问题,第一个问题(正如Lorenzo Donati指出的)是,您将实际调用包装在了
random()
中,给了您一个从未真正做过任何事情的块(woops)

第二个是调用两次
math.random()
,得到两个单独的值;这意味着两种测试都不可能是真的

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

功能等待(秒)
本地启动=os.time()
重复此操作,直到os.time()>开始+秒
结束
随机函数(机会)
局部r=math.random()
如果r启动+秒
结束
随机函数(机会)
局部r=math.random()

打印(R)请格式化代码,使其清晰易读。