Timeouts in AngelScript

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in AngelScript requires careful management of time and asynchronous operations.

void main()
{
    // For our example, suppose we're executing an external
    // call that returns its result after 2 seconds.
    // We'll simulate this with a timer.
    Timer@ timer1 = Timer();
    timer1.set(2000, false);
    
    // We'll use a dictionary to store our result
    dictionary result1;
    
    // This function simulates our async operation
    void asyncOperation1(dictionary@ result)
    {
        result["value"] = "result 1";
    }
    
    // Start our timer
    timer1.start();
    
    // We'll use a while loop to implement our timeout
    uint64 startTime = getSystemTime();
    while(!timer1.isFinished())
    {
        // Check if we've exceeded our timeout
        if(getSystemTime() - startTime > 1000)
        {
            print("timeout 1\n");
            return;
        }
        
        // Yield to allow other operations
        yield();
    }
    
    // If we've reached here, our operation completed
    asyncOperation1(result1);
    print(result1["value"] + "\n");
    
    // For the second example, we'll use a longer timeout
    Timer@ timer2 = Timer();
    timer2.set(2000, false);
    
    dictionary result2;
    
    void asyncOperation2(dictionary@ result)
    {
        result["value"] = "result 2";
    }
    
    timer2.start();
    
    startTime = getSystemTime();
    while(!timer2.isFinished())
    {
        if(getSystemTime() - startTime > 3000)
        {
            print("timeout 2\n");
            return;
        }
        
        yield();
    }
    
    asyncOperation2(result2);
    print(result2["value"] + "\n");
}

Running this program shows the first operation timing out and the second succeeding.

timeout 1
result 2

In this AngelScript version, we use Timer objects to simulate asynchronous operations. The while loops with yield() calls act similarly to the select statement in the original example, allowing us to check for timeouts while waiting for the operation to complete.

Note that AngelScript doesn’t have built-in concurrency primitives like channels or goroutines, so we’ve had to simulate these concepts using timers and asynchronous functions. The getSystemTime() function is used to implement the timeout logic.

This example demonstrates how to implement basic timeout functionality in AngelScript, although the exact implementation may vary depending on the specific AngelScript environment and available libraries.