Search code examples
randomlua

i need help getting seed = os.clock to output a integer


I am trying to get a random number generation but keep getting this syntax.

lua5.3: Main.lua:3: bad argument #1 to 'random' (number has no integer representation)
stack traceback:
    [C]: in function 'math.random'
    Main.lua:3: in main chunk
    [C]: in ?

I tried to use this to get a random number but it doesn`t have a integer representation.

seed = os.clock()
print(seed)
e = math.random(seed)
print(e)

Solution

  • I'll be assuming Lua 5.4. Quoting the reference manual:

    math.randomseed ([x [, y]])

    When called with at least one argument, the integer parameters x and y are joined into a 128-bit seed that is used to reinitialize the pseudo-random generator; equal seeds produce equal sequences of numbers. The default for y is zero.

    When called with no arguments, Lua generates a seed with a weak attempt for randomness.

    This function returns the two seed components that were effectively used, so that setting them again repeats the sequence.

    To ensure a required level of randomness to the initial state (or contrarily, to have a deterministic sequence, for instance when debugging a program), you should call math.randomseed with explicit arguments.

    math.random ([m [, n]])

    When called without arguments, returns a pseudo-random float with uniform distribution in the range [0,1). When called with two integers m and n, math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. The call math.random(n), for a positive n, is equivalent to math.random(1,n). The call math.random(0) produces an integer with all bits (pseudo)random.

    os.clock()

    Returns an approximation of the amount in seconds of CPU time used by the program, as returned by the underlying ISO C function clock.

    So os.clock() returns a fractional value like 0.002814; it is not rounded/floored to seconds. math.random expects an integer like 42 and thus errors as you don't provide an integer, but rather a fractional number.

    math.random also doesn't expect a "seed"; it expects a range. Use math.randomseed to seed math.random. As the docs tell you, if you don't care about the "randomness" of the seed, just call math.randomseed() without arguments.

    You probably want to use os.time() for seeding. os.time() produces an integer (typically the seconds since the UNIX epoch). The caveat is that invocations during the same second will use the same seed.