0

I am trying to generate a random number, every random seconds (the final purpose would be to change the color of a block from time to time, randomly).

For that, I am using the Hump library (http://vrld.github.io/hump/#hump.timer).

Here is my code at the moment, I am true beginner in LUA/Love2d coding. It generates a number, and displays it every seconds, instead of every random seconds... (but the random seconds is also generated). I don't really understand why it is not working.

local Timer = require "timer"

function love.load()
    text="t"
    number2=1
end

local f = function()
math.randomseed(os.time())
    number = math.random( 2,10 )
    text="in " .. number2 .. " seconds (random)...  random number =" .. number
    return true
end

function love.update(dt)

    number2 = math.random( 2,4 ) 
    Timer.update(number2)
    Timer.addPeriodic(number2, f)
end

function love.draw()
    love.graphics.print( text, 330, 300 )
end

Thanks for any help !

4
  • 3
    Call math.randomseed(os.time()) just once in your program. Commented Jun 11, 2014 at 19:32
  • my bad, I removed the one in the love.update but the issue remains. Commented Jun 11, 2014 at 19:39
  • In the updated code, you are still calling f in love.update, which means math.randomseed is still called more than once. Commented Jun 12, 2014 at 0:39
  • ok I understand better now. I needed to also move the 'number2' in a function and not call 'f' in 'love.update'... but I had an issue where the text was printed every 0.1seconds, so I changed the code again and came up with something alsmot similar to what Henri Ilgen suggested below! Commented Jun 12, 2014 at 17:48

1 Answer 1

1

While I am not familiar with Hump, it seems that you can easily use the timer's add function for your purpose, as it will call the function exactly once after x seconds, allowing you to schedule the next execution with a different delay:

local timer = require("timer")
local text = ""

local function tick()
  -- Generate random number
  local newNumber = math.random(2, 10)
  local newDelay  = math.random(2,  4)
  text = ("Current number: %d, next in %d seconds!"):format(newNumber, newDelay)

  -- Actually schedule the next call
  timer.add(newDelay, tick)
end


function love.load()
  tick()
end

function love.update(dt)
  timer.update(dt)
end

function love.draw()
  love.graphics.print(text, 330, 300)
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.