这是我目前所拥有的,但似乎每次我尝试运行它时,它都会关闭。
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/