1

In the beginning of my program I initialise the random number generator with:

math.randomseed (os.time ())
math.random (); math.random (); math.random ()

In another function, I want to call math.random when the variable pc has a value of nil:

function playervspc2 ()
    if pc == nil then
        pc = math.random (1, 7)
    end
end

This does give a random number, but repeats this number when playervspc2 is called again during runtime:

while win == 0 do
    playervspc1 ()
    windetect (playername)
    if win == 1 then
        break
    end
    playervspc2 ()
    windetect ("The PC")
end

When math.random is called without the condition that pc == nil, it gives perfectly random numbers. I have checked that pc is really nil just before the the if pc == nil statement starts.

1

2 Answers 2

2

I would say that second call to your function doesn't do anything, as pc (which is probably global value, is not nil anymore, instead it has a value which was randomly generated first time, thus the condition if pc == nil is false and nothing happens. Change it to

function playervspc2 ()
  pc = math.random(1,7)
end

And it will provide you with random pc every time you call it.

0

Not sure what you mean by using pc. Here is my answer based on what I understood:

It looks like pc is local variable and has not been defined before it is used.

Try defining pc from the calling module, assign pc an initial value then pass that to the called module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.