Core.yield: Difference between revisions

From GiderosMobile
No edit summary
No edit summary
 
(17 intermediate revisions by 2 users not shown)
Line 1: Line 1:
__NOTOC__
__NOTOC__
'''Available since:''' Gideros 2016.06<br/>
'''Available since:''' Gideros 2016.06<br/>
'''Class:''' [[Core]]<br/>
=== Description ===
=== Description ===
<translate>Yield function running as background task.
Yields the function running as background task.
<syntaxhighlight lang="lua">
Core.yield(state)
</syntaxhighlight>


Core.yield([number of seconds to wait])
Core.yield([number of seconds to wait])
Core.yield(true) -- yield for a single frame and disable auto yield
Core.yield(true) -- yield for a single frame and disable auto yield
Core.yield(false) -- don't yield now, but reenable autoyield</translate>
 
<source lang="lua">
Core.yield(false) -- don't yield now, but reenable autoyield
Core.yield(state)
 
</source>
In Gideros, Core.yield(''number'') pauses the execution of the current asynchronous task or background thread for ''number'' seconds before resuming it. How it Works:
*Time-based Delay: Passing a number like 1 tells the engine to suspend the running coroutine/async function (started via Core.asyncCall or Core.asyncThread) and wait for that many seconds to pass in real time
*Non-blocking: While this specific task is paused, the main game loop and other engine processes continue running smoothly without freezing
 
Alternative Arguments:
*Core.yield(true) pauses execution until the very next frame
*Core.yield(number) pauses execution for the specified number of seconds
 
Passing false to Core.yield() acts as a soft yield. Instead of waiting for a specific duration (number) or waiting specifically for the next frame render (true), Core.yield(false) simply yields execution immediately to let other tasks run, then resumes on the very same frame if there is processing time left.
 
This is highly useful for heavy background computations (like procedural map generation, pathfinding, or heavy math operations) where you want to break a huge loop into chunks so the game doesn't stutter, but you still want it to finish as quickly as possible.
 
'''Summary of Core.yield behaviors''':
*Core.yield(number): ''Delay Behavior'': Pauses for X seconds. ''Primary Use Case'': Timers, cooldowns, delayed events
*Core.yield(true): ''Delay Behavior'': Pauses until the next graphics frame.. ''Primary Use Case'': Frame-by-frame visual animations and moving objects
*Core.yield(false): ''Delay Behavior'': Pauses momentarily to clear the task queue, then resumes ASAP. ''Primary Use Case'': Distributing heavy math loops across time without freezing the screen
 
=== Parameters ===
=== Parameters ===
'''state''': (number or boolean) <translate>number of seconds to yield or boolean to enable/disable auto yield</translate> <br/>
'''state''': (number or boolean) number of seconds to yield or boolean to enable/disable auto yield<br/>
 
=== Examples ===
<syntaxhighlight lang="lua">
local txt1_noads = TextField.new(nil, "no ads")
local txt2_plusincome = TextField.new(nil, "plus income")
local btn_OK = TextField.new(nil, "OK")
-- position
txt1_noads:setPosition(64, 64*1)
txt2_plusincome:setPosition(64, 64*3)
btn_OK:setPosition(64, 64*5)
-- scale
local FontScale = 4
local tempFontScale = 8
txt1_noads:setScale(FontScale)
txt2_plusincome:setScale(FontScale)
btn_OK:setScale(FontScale)
-- order
stage:addChild(txt1_noads)
stage:addChild(txt2_plusincome)
stage:addChild(btn_OK)
 
local function scaleTextsAndBtn()
Core.yield(2)
txt1_noads:setScale(tempFontScale)
Core.yield(1)
txt1_noads:setScale(FontScale)
 
Core.yield(1)
txt2_plusincome:setScale(tempFontScale)
Core.yield(1)
txt2_plusincome:setScale(FontScale)
 
Core.yield(1)
btn_OK:setScale(tempFontScale)
Core.yield(0.5)
btn_OK:setScale(FontScale)
end
Core.asyncCall(scaleTextsAndBtn)
</syntaxhighlight>
 
'''A simple function that counts down from a given number'''
<syntaxhighlight lang="lua">
local function startCountdown(seconds)
    Core.asyncCall(function()
        print("Timer started!")
       
        for i = seconds, 1, -1 do
            print("Time remaining: " .. i .. " seconds")
           
            -- Pause this specific task for exactly 1 second
            Core.yield(1)
        end
       
        print("Time's up! 🚀")
    end)
end
 
-- Start a 5-second countdown
startCountdown(5)
</syntaxhighlight>
Key Takeaways from this Example
*Sequential execution: The for loop looks like traditional synchronous code, but Core.yield(1) cleanly injects a delay between each iteration.
*No game freezing: While this timer is counting down, your players can still touch buttons, sprites can animate, and physics will continue to update normally.
 
'''Core.yield(true)'''
<syntaxhighlight lang="lua">
-- Assume 'mySprite' is an existing image or shape on the stage
local mySprite = Bitmap.new(Texture.new("character.png"))
stage:addChild(mySprite)
mySprite:setPosition(0, 200)
 
-- Launch the animation inside an async thread
Core.asyncCall(function()
    print("Animation Start")
 
    -- Move the sprite from X=0 to X=300
    while mySprite:getX() < 300 do
        local currentX = mySprite:getX()
 
        -- Move 2 pixels forward every single frame
        mySprite:setX(currentX + 2)
 
        -- Pause here and wait until the next game frame is drawn
        Core.yield(true)
    end
 
    print("Animation Complete! 🎉")
end)
</syntaxhighlight>
Why Use Core.yield(true) Over Event.ENTER_FRAME?
 
Traditionally, game loops use Event.ENTER_FRAME listeners. While event listeners are great, Core.yield(true) provides significant benefits for multi-step animations:
#Linear Logic: You can sequence actions naturally. For example, you can slide a character right, Core.yield(1) to pause for a second, and then fade them out using a Core.yield(true) loop—all within a single block of code
#Local Variables Retention: All your loop variables stay safely within the function scope. You don't have to pollute your global space with variables like isAnimating or targetX
 
'''Core.yield(false), heavy Loop Optimization Example'''
 
If you run a heavy loop normally, the engine freezes until it finishes. By using Core.yield(false) paired with a timer check, you can run the loop at maximum speed, pause to let the engine breathe/render if a frame is taking too long, and pick right back up:
<syntaxhighlight lang="lua">
local function performHeavyCalculations()
    Core.asyncCall(function()
        print("Starting massive math calculation...")
       
        local startTime = os.clock()
        local totalIterations = 1000000
       
        for i = 1, totalIterations do
            -- Simulate heavy calculations
            local data = math.sin(i) * math.cos(i)
           
            -- Every 5000 items, check if we've spent too much time on this frame
            if i % 5000 == 0 then
                local elapsed = os.clock() - startTime
               
                -- If this loop has hogged the CPU for more than 2 milliseconds (0.002s)
                if elapsed > 0.002 then
                    -- Yield so the engine can process touches, audio, and graphics
                    Core.yield(false)
                   
                    -- Reset our stopwatch for the next chunk
                    startTime = os.clock()
                end
            end
        end
       
        print("Calculations finished successfully without dropping frames! 🎉")
    end)
end
 
performHeavyCalculations()
</syntaxhighlight>
 
=== See also ===
'''[[Core.asyncCall]]'''
 
{{Core}}

Latest revision as of 10:08, 29 September 2026

Available since: Gideros 2016.06
Class: Core

Description

Yields the function running as background task.

Core.yield(state)

Core.yield([number of seconds to wait])

Core.yield(true) -- yield for a single frame and disable auto yield

Core.yield(false) -- don't yield now, but reenable autoyield

In Gideros, Core.yield(number) pauses the execution of the current asynchronous task or background thread for number seconds before resuming it. How it Works:

  • Time-based Delay: Passing a number like 1 tells the engine to suspend the running coroutine/async function (started via Core.asyncCall or Core.asyncThread) and wait for that many seconds to pass in real time
  • Non-blocking: While this specific task is paused, the main game loop and other engine processes continue running smoothly without freezing

Alternative Arguments:

  • Core.yield(true) pauses execution until the very next frame
  • Core.yield(number) pauses execution for the specified number of seconds

Passing false to Core.yield() acts as a soft yield. Instead of waiting for a specific duration (number) or waiting specifically for the next frame render (true), Core.yield(false) simply yields execution immediately to let other tasks run, then resumes on the very same frame if there is processing time left.

This is highly useful for heavy background computations (like procedural map generation, pathfinding, or heavy math operations) where you want to break a huge loop into chunks so the game doesn't stutter, but you still want it to finish as quickly as possible.

Summary of Core.yield behaviors:

  • Core.yield(number): Delay Behavior: Pauses for X seconds. Primary Use Case: Timers, cooldowns, delayed events
  • Core.yield(true): Delay Behavior: Pauses until the next graphics frame.. Primary Use Case: Frame-by-frame visual animations and moving objects
  • Core.yield(false): Delay Behavior: Pauses momentarily to clear the task queue, then resumes ASAP. Primary Use Case: Distributing heavy math loops across time without freezing the screen

Parameters

state: (number or boolean) number of seconds to yield or boolean to enable/disable auto yield

Examples

local txt1_noads = TextField.new(nil, "no ads")
local txt2_plusincome = TextField.new(nil, "plus income")
local btn_OK = TextField.new(nil, "OK")
-- position
txt1_noads:setPosition(64, 64*1)
txt2_plusincome:setPosition(64, 64*3)
btn_OK:setPosition(64, 64*5)
-- scale
local FontScale = 4
local tempFontScale = 8
txt1_noads:setScale(FontScale)
txt2_plusincome:setScale(FontScale)
btn_OK:setScale(FontScale)
-- order
stage:addChild(txt1_noads)
stage:addChild(txt2_plusincome)
stage:addChild(btn_OK)

local function scaleTextsAndBtn()
	Core.yield(2)
	txt1_noads:setScale(tempFontScale)
	Core.yield(1)
	txt1_noads:setScale(FontScale)

	Core.yield(1)
	txt2_plusincome:setScale(tempFontScale)
	Core.yield(1)
	txt2_plusincome:setScale(FontScale)

	Core.yield(1)
	btn_OK:setScale(tempFontScale)
	Core.yield(0.5)
	btn_OK:setScale(FontScale)
end
 
Core.asyncCall(scaleTextsAndBtn)

A simple function that counts down from a given number

local function startCountdown(seconds)
    Core.asyncCall(function()
        print("Timer started!")
        
        for i = seconds, 1, -1 do
            print("Time remaining: " .. i .. " seconds")
            
            -- Pause this specific task for exactly 1 second
            Core.yield(1) 
        end
        
        print("Time's up! 🚀")
    end)
end

-- Start a 5-second countdown
startCountdown(5)

Key Takeaways from this Example

  • Sequential execution: The for loop looks like traditional synchronous code, but Core.yield(1) cleanly injects a delay between each iteration.
  • No game freezing: While this timer is counting down, your players can still touch buttons, sprites can animate, and physics will continue to update normally.

Core.yield(true)

-- Assume 'mySprite' is an existing image or shape on the stage
local mySprite = Bitmap.new(Texture.new("character.png"))
stage:addChild(mySprite)
mySprite:setPosition(0, 200)

-- Launch the animation inside an async thread
Core.asyncCall(function()
    print("Animation Start")

    -- Move the sprite from X=0 to X=300
    while mySprite:getX() < 300 do
        local currentX = mySprite:getX()

        -- Move 2 pixels forward every single frame
        mySprite:setX(currentX + 2)

        -- Pause here and wait until the next game frame is drawn
        Core.yield(true)
    end

    print("Animation Complete! 🎉")
end)

Why Use Core.yield(true) Over Event.ENTER_FRAME?

Traditionally, game loops use Event.ENTER_FRAME listeners. While event listeners are great, Core.yield(true) provides significant benefits for multi-step animations:

  1. Linear Logic: You can sequence actions naturally. For example, you can slide a character right, Core.yield(1) to pause for a second, and then fade them out using a Core.yield(true) loop—all within a single block of code
  2. Local Variables Retention: All your loop variables stay safely within the function scope. You don't have to pollute your global space with variables like isAnimating or targetX

Core.yield(false), heavy Loop Optimization Example

If you run a heavy loop normally, the engine freezes until it finishes. By using Core.yield(false) paired with a timer check, you can run the loop at maximum speed, pause to let the engine breathe/render if a frame is taking too long, and pick right back up:

local function performHeavyCalculations()
    Core.asyncCall(function()
        print("Starting massive math calculation...")
        
        local startTime = os.clock()
        local totalIterations = 1000000
        
        for i = 1, totalIterations do
            -- Simulate heavy calculations
            local data = math.sin(i) * math.cos(i)
            
            -- Every 5000 items, check if we've spent too much time on this frame
            if i % 5000 == 0 then
                local elapsed = os.clock() - startTime
                
                -- If this loop has hogged the CPU for more than 2 milliseconds (0.002s)
                if elapsed > 0.002 then
                    -- Yield so the engine can process touches, audio, and graphics
                    Core.yield(false) 
                    
                    -- Reset our stopwatch for the next chunk
                    startTime = os.clock()
                end
            end
        end
        
        print("Calculations finished successfully without dropping frames! 🎉")
    end)
end

performHeavyCalculations()

See also

Core.asyncCall