function - 试图在 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 then
  print ("no")
  end

random(0.5)
wait(5)
end

这是完整的上下文。

最佳答案

该代码存在一些问题,第一个(正如 Lorenzo Donati 指出的那样)是您将实际调用包装在 random() 中,给您提供了一个从未实际执行过的 block 任何东西(呜呜)。

第二个是你两次调用 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)

关于function - 试图在 Lua 中随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412740/

相关文章:

javascript - 有必要在 Angular 指令链接内命名函数吗?

ios - 我需要随机的几何形状、 Material 或其他东西吗? - 场景套件, swift

lua - Lua 中的范围规则

lua - 有没有办法并行运行 Busted 测试套件?

编织到单词时,Rmarkdown 无法找到 lua 过滤器

javascript - 排序数组问题

Python函数直接改变列表,而不返回它

c - 我如何使用从 c 中的函数返回的值

java - 从 0-9 获得四个唯一随机数的最佳方法是什么?

Php日历星期随机用户计算