Executing a function with a timer with a random value

I wanted to make a timer that executes the function below when it hits zero, the timer would have a random value between 10 and 20 and when it hits zero a function is called. I tried looking at the timer API documentation but I don’t understand it well enough to see how it would help me in my program. What I originally planned was to define a variable that holds a random value between 10 and 20 and then decrease it by 1 every second and then execute the function when it hits Zero but I don’t know how to do this. please help :frowning:

image

Typing this on my phone so might need tweaking!

Say you have your random variable:

local countdown = math.random(10,20)

Then you could use the timer something like this (checking every second):

timer.delay(1, true, function()
    countdown = countdown - 1
    if countdown <= 0 then
        --do things here
    end
end)
2 Likes

This should be enough:

local delay = math.random(10, 20)
timer.delay(delay, false, check_lines)
5 Likes

Thank you for both of your help! But I ran into another problem, my project is basically a variation of Tetris, The timer code you guys gave me works but it only erases one line at a time in the game, so I added a while loop to check_lines to erase all lines simultaneously but I keep getting this error and I don’t know what causes it

image

image

You’ve forgotten a matching “end” for the function you created in the delay call

2 Likes

Defold built in editor really insufficient*. Editor completes built in fuctions but it doesn’t help for variables. If I wrote a variable it must be auto complete it when I rewrite. And more… Here is not the place for this.

You can try Visual Studio Code with Defold code snippets extension.

I tried using your method because it was more versatile for my program as I have a variable I can interact with but It’s setting off the function as soon as it can and not in 10,20 seconds like i hoped

image

I just tested this in the init() of a script and it works:

local delay = math.random(10,20)
timer.delay(1, true, function()
	delay = delay - 1
	if delay <= 0 then
		print("now")
	else
		print("not now")
	end
end)

Where and how often are you calling next_block()? You define a new local variable “delay” and a new timer every time you do so, and I suspect maybe that’s the reason things aren’t working.

Edit: I should have also mentioned that @britzl 's method is better than what I originally posted. The whole purpose of a timer is to have an arbitrary delay, so I’m not sure why I suggested having a repeating timer tick on a one second interval to check if a delay has passed. The only reason I can think of is to have something occur when the timer isn’t finished (like my “not now” print above).

1 Like