Cinere
Cinere

Reputation: 23

Attempting to make a random choice in Lua

This is what I have so far, but it seems that everytime I attempt to run it, it closes.

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

That is the full context.

Upvotes: 2

Views: 1060

Answers (2)

Textmode
Textmode

Reputation: 508

Theres a few problems with that code, the first (as Lorenzo Donati points out) is that you've wrapped the actual invocations inside of random(), giving you a chunk that never actually does anything (woops).

The second is that you are invoking math.random() twice, giving you two separate values; this means that its perfectly possible for neither test to be true.

The third is minor: You are making two tests for an either-or choice; the first test would tell us everything we need to know:

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)

and just for kicks, we can replace the if-block with a conditional value, thus:

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)

Upvotes: 8

Probably you meant to write this:

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)

Upvotes: 3

Related Questions