Search code examples
randomluainteger

How can I make it so a global variable with "math.random()" will give me a new number every time? (Lua)


Every time I use a variable (eggs, spam, hams, and yams) and use a random function from the math library (math.random(100)) in Lua, it keeps giving the same exact number it randomized the first time. How can I edit the code so it will give a new randomized integer every time it is run?

spam = math.random(100)
eggs = math.random(100)
yams = math.random(100)
hams = math.random(100)

if eggs > spam then
  print("eggs are better than spam")
end

if spam > eggs then
  print("spam is better than eggs")
end

if yams > hams then
  print("yams are better than hams")
end

if hams > yams then
  print("hams are better than yams")
end

print(spam)
print(hams)
print(eggs)
print(yams)

I Tried using a goto function to a label, but Lua didn't recognize Label. Like this:

:: Label ::
--further code
goto Label

Solution

  • First, set the seed and than roll the Dice before return a random...

    -- oooh.lua
    math.randomseed(math.random(os.time()))
    
    math.random() -- Roll
    math.random() -- Roll
    math.random() -- Roll
    
    local one_out_of_hundred = math.random(1, 100)
    
    print(("%s:\t%d"):format(_VERSION, one_out_of_hundred))
    
    return(one_out_of_hundred)
    

    Than you can check it against different Lua Versions...

    € /bin/lua oooh.lua 
    Lua 5.1:    56
    € /bin/lua oooh.lua 
    Lua 5.1:    38
    € /bin/lua oooh.lua 
    Lua 5.1:    20
    € /usr/bin/lua oooh.lua 
    Lua 5.3:    15
    € /usr/bin/lua oooh.lua 
    Lua 5.3:    15
    € /usr/bin/lua oooh.lua 
    Lua 5.3:    57
    € /usr/bin/lua oooh.lua 
    Lua 5.3:    51
    € /usr/local/bin/lua oooh.lua 
    Lua 5.4:    43
    € /usr/local/bin/lua oooh.lua 
    Lua 5.4:    91
    € /usr/local/bin/lua oooh.lua 
    Lua 5.4:    66
    

    Second, as i know only Lua 5.4 allow goto labels
    See: https://www.lua.org/manual/5.4/manual.html#3.3.4
    Try: To find it in other Lua Version References ;-)