Class: Thread

Thread (func) Thread constructor.
Thread.runOnMain (func, ...) Immediately executes the given function on the main thread.
Thread.callback (func, ignoreDebugger) Wraps a function to ensure it is executed on a thread.
Thread.wrapMain (func) Wraps a function to ensure it is executed on the main thread.
Thread.current () Get the current thread.
Thread.allThreads () Get all active threads.
Thread.sleep (duration) Put the current thread to sleep for a period of time.
Thread:detach () Remove a thread from the thread dispatch loop.
Thread:attach () Add a previously detached thread to the thread dispatch loop.
yield (fast) Yield execution on the current thread.
abort ()

Module: Preprocessor

Preprocess (srcAsset, print) Preprocesses and loads the given source asset.
DEF (name, value) Adds a preprocessor defined value.
UNDEF (id) Undefines a value previously defined with DEF(id).
IF (id) Start a conditional compilation block.
END () End a conditional compilation block.

Class: Semaphore

Semaphore () Semaphore constructor.
Semaphore:signal () Increments the semaphore value.
Semaphore:signalAll () Increase the semaphore value by the number of threads currently waiting on this semaphore.
Semaphore:wait (fast) Yield the current thread until the semaphore value is > 0.

Class: Promise

Promise (func) Promise constructor.
Promise:resolve (...) Resolve the promise with the provided values.
Promise:reject (err) Reject the promise with the provided error.
Promise:reset () Resets the promise to the unfullfilled state.
Promise:next (onFullfilled, onRejected) Chain handler functions to be called when the promise is resolved.
Promise:catch (onRejected)
Promise:finally (onFinally)
Promise.all (promises)
Promise:await (fast)
async (func) Returns a wrapped function that when called will return a promise.
await (promise, fast) Wait for the given promise to resolve.

Module: http

http.request (url, success, fail, parameters) Identical to the built-in function but callbacks will be executed on a thread to allow for debugging within the callbacks.
http.requestProm (url, parameters) Identical to the built-in function but returns results using a Promise object.
http.requestSync (url, parameters) Identical to the built-in function but blocks waiting until the request completes (success or failure).

Module: Util

registerTerminator (func) Registers a function to be called when the project is stopped.
addTerminator (func) Alias of registerTerminator().
unregisterTerminator (func) Removes a previously registered function from the list of terminator functions.
removeTerminator (func) Alias of unregisterTerminator().
enableLogging (silent, logfile) Enables logging all 'print' output to the project tab with the given name.

Module: Debugger

dbg (condition) Breaks into the debugger.
c () Exit the debugger and continue execution.
l (nameOrLevel, level) View local variables.
sl (name, value, level) Set a local variable.
t () Print the backtrace again.

Module: AutoDoc

AutoDoc (display) Generates HTML documentation from the current project source and optionally displays it in a Fullscreen webview.

Class: Thread

Cooperative thread object based on Lua coroutines.
Thread (func)
Thread constructor.

Parameters:

  • func Function to execute on the new thread.

Usage:

  • function setup()
        -- Start a thread that will print its value once per frame
        Thread(function()
    
            -- Our thread local counter
            local i = 0
    
            -- Loop forever
            while true do
    
                -- Print and increment counter
                print("Thread counter", i)
                i = i + 1
                
                -- Yield the thread to stop execution for the current frame
                yield()
            end
        end)
    end
Thread.runOnMain (func, ...)
Immediately executes the given function on the main thread.

Various Codea functions do not function correctly when used from a coroutine so use this to temporarily hand execution back to the main thread.

Parameters:

  • func Function to run on the main thread.
  • ... Parameters to supply to the provided function.

Usage:

  • -- Takes a screenshot from the main thread.
    Thread.runOnMain(function()
        screenshot = viewer.snapshot()
    end)
  • -- Prints a message from the main thread.
    Thread.runOnMain(print, "Hello main thread!")
Thread.callback (func, ignoreDebugger)
Wraps a function to ensure it is executed on a thread.

By default wrapped functions will not execute (or be queued) if the debugger is active. Set ignoreDebugger to true if the callback should be executed regardless of the debugger.

Parameters:

  • func The function to be wrapped.
  • ignoreDebugger If true then the function will execute regardless of the state of the debugger.

Returns:

    The wrapped function.

Usage:

  • local function success(data, statusCode, headers)
        print(statusCode)
    end
    
    -- If this weren't wrapped, we couldn't call
    -- dbg() from inside the callback
    local failure = Thread.callback(function(err)
        print(err)
        dbg()
    end)
    
    Thread.runOnMain(
        http.request,
        "https://codeawebrepo.co.uk/manifest.json",
        success, failure
    )
Thread.wrapMain (func)
Wraps a function to ensure it is executed on the main thread.

Parameters:

  • func The function to wrap.

Returns:

    The wrapped function
Thread.current ()
Get the current thread.

Returns:

    The currently running thread, or nil if the main thread is running.
Thread.allThreads ()
Get all active threads.

Returns:

    A table containing all active threads.
Thread.sleep (duration)
Put the current thread to sleep for a period of time.

Parameters:

  • duration Duration of sleep in seconds
Thread:detach ()
Remove a thread from the thread dispatch loop.

This eliminates all overhead for an idle thread. If you wish to resume execution on the thread, ensure you call attach().
Thread:attach ()
Add a previously detached thread to the thread dispatch loop.
yield (fast)
Yield execution on the current thread.
This allows cooperative multitasking during a frame & across frames.

Parameters:

  • fast (default false)
    When false, execution will not resume on this thread until the next frame at the earliest.
    When true, execution can return to this thread in the current frame.
abort ()
Halts all threads and stops execution

Module: Preprocessor

Lua preprocessor allowing for basic conditional compilation and text substitution at compile time.

This allows for code segments to be entirely omitted from the executed code which can be incredibly useful when you want your code to be performant AND debugable.
Preprocess (srcAsset, print)
Preprocesses and loads the given source asset.

Parameters:

  • srcAsset The Codea asset key corresponding to the file to be loaded.
  • print If true, the final processed source code will be printed to the console.

Usage:

  • -- Preprocessing should always be done at the top
    -- of your source file in an if statement like this.
    -- If this is not done inside an if statement this will not work.
    if Preprocess(asset.Main) then return end
    
    -- Preprocessor defines
    DEF(DEBUG, true)
    
    -- Strings must be within a string themselves
    -- in order to be inserted correctly into the source code.
    DEF(kWelcomeMessage, "'Welcome to the preprocessor!'")
    
    function setup()
        print(kWelcomeMessage)
        IF(DEBUG)
            -- Only include this print statement when the 'DEBUG' preprocessor
            -- value is true.
            print("Debug message")
        END()
    end
DEF (name, value)
Adds a preprocessor defined value.
A value set using this function will not be a conventional variable, rather at compile time instances of the key in the source code will be replaced with the value provided to this function.

Parameters:

  • id The name given to the provided value.
  • value The value to replace occurances with. This can be a string, true, false or nil.

Usage:

  • DEF(kWelcomeMessage, '"Hello Codea"')
    
    print(kWelcomeMessage) -- After preprocessing becomes 'print("Hello Codea")'
  • DEF(kExperimentalFeatures, false)
    
    ...
    
    IF(kExperimentalFeatures)
        -- Do unstable experimental thing. Funny that!
        ...
    END()
UNDEF (id)
Undefines a value previously defined with DEF(id).

Parameters:

  • id The name of the value to be undefined.
IF (id)
Start a conditional compilation block.
END ()
End a conditional compilation block.

Class: Semaphore

Semaphore object for thread coordination
Semaphore ()
Semaphore constructor.
Semaphore:signal ()
Increments the semaphore value.
Semaphore:signalAll ()
Increase the semaphore value by the number of threads currently waiting on this semaphore.
Semaphore:wait (fast)
Yield the current thread until the semaphore value is > 0.
This will return immediately if the semaphore value is already > 0.

Parameters:

  • fast (default false)
    When false, execution will not resume on this thread until the next frame at the earliest.
    When true, execution can return to this thread in the current frame.

Class: Promise

JavaScript like promises
Promise (func)
Promise constructor.

Parameters:

  • func Function to execute on a new thread. This function should accept 2 parameters, resolve & reject.

Returns:

    New Promise object
Promise:resolve (...)
Resolve the promise with the provided values.

Parameters:

  • ... values to resolve the promise with. These will be passed to any chained promises.
Promise:reject (err)
Reject the promise with the provided error.

Parameters:

  • err Error to reject the promise with. This will be passed to any chained promises.
Promise:reset ()
Resets the promise to the unfullfilled state.

Note: This does NOT remove or reset chained promises.
Promise:next (onFullfilled, onRejected)
Chain handler functions to be called when the promise is resolved.
The next() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

Parameters:

  • onFullfilled (optional) A Function called if the Promise is fulfilled. This function can have multiple arguments, the fulfillment values. If it is not a function, it is internally replaced with an "Identity" function (it returns the received argument).
  • onRejected (optional) A Function called if the Promise is rejected. This function has one argument, the rejection reason. If it is not a function, it is internally replaced with a "Thrower" function (it throws an error it received as argument).

Returns:

    A new promise to be resolved with the result of onFullfilled or onRejected.
Promise:catch (onRejected)
Promise:finally (onFinally)
Promise.all (promises)
Promise:await (fast)
async (func)
Returns a wrapped function that when called will return a promise.

The called function will be executed asynchronously on a new thread and the returned promise will be resolved with the result of the function call.

This allows any function to be turned into an asynchronous function with little effort.

Parameters:

  • func The function to be wrapped.

Returns:

    The wrapped function
await (promise, fast)
Wait for the given promise to resolve.

Parameters:

  • promise The promise to wait for.
  • fast (default false)
    When false, execution will not resume on this thread until the next frame at the earliest.
    When true, execution can return to this thread in the current frame.

Returns:

    The values the promise was resolved with.

Module: http

Modifications to Codea's built-in http.request function.
http.request (url, success, fail, parameters)
Identical to the built-in function but callbacks will be executed on a thread to allow for debugging within the callbacks.

Parameters:

  • url URL to request
  • success Callback to be executed in the case of a successful request.
  • fail Callback to be executed in the case of a failed request.
  • parameters Request parameters.
http.requestProm (url, parameters)
Identical to the built-in function but returns results using a Promise object.

Parameters:

  • url URL to request
  • parameters Request parameters.

Returns:

    Promise object that will be resolved or rejected with the results of the request.
http.requestSync (url, parameters)
Identical to the built-in function but blocks waiting until the request completes (success or failure).

Parameters:

  • url URL to request
  • parameters Request parameters.

Returns:

    In the case of a successful request, a table in the form { response, statusCode, headers }
    In the case of a failed request, a table in the form { nil, errorMessage }

Module: Util

Various useful functions & utilities.
registerTerminator (func)
Registers a function to be called when the project is stopped.
This is akin to Codea's 'willClose()' function but allows multiple callback functions to be registered.

Parameters:

  • func The function to be registered as a terminator.
addTerminator (func)
Alias of registerTerminator().
unregisterTerminator (func)
Removes a previously registered function from the list of terminator functions.

Parameters:

  • func The function to be unregistered.
removeTerminator (func)
Alias of unregisterTerminator().
enableLogging (silent, logfile)
Enables logging all 'print' output to the project tab with the given name.

This also prefixes all output with the current time.

Parameters:

  • silent If true, nothing will be printed to the sidepanel, only the logfile.
  • logfile Name of the project tab to write our log to.

Module: Debugger

dbg (condition)
Breaks into the debugger. If a condition is provided, the debugger is only triggered if the condition evaluates to true.

Parameters:

  • condition (optional) If true, the debugger will be triggered.
c ()
Exit the debugger and continue execution.

Important: This is only to be called manually using the Codea sidepanel while the debugger is active.
l (nameOrLevel, level)
View local variables.

When called with no arguments this prints all local variables at the stack frame of the active 'dbg()' call.

Note: When listed, string values are omitted. Use l("<variable_name>", [stack_level]) to view the full value.

Important: This is only to be called manually using the Codea sidepanel while the debugger is active.

Parameters:

  • nameOrLevel (optional) Name of the variable to read OR stack level to list.
  • level (optional) Level to search for the given local variable name.

Usage:

  • -- Prints all local variables in the current stack frame
    l()
  • -- Prints all local variables in the next stack frame up (1 == current frame)
    l(2)
  • -- Prints the value of the local variable 'i'
    -- in the first stack frame it is found.
    l("i")
  • -- Prints the value of the local variable 'i' in the 3rd stack frame.
    l("i", 3)
sl (name, value, level)
Set a local variable.

Important: This is only to be called manually using the Codea sidepanel while the debugger is active.
t ()
Print the backtrace again.

Important: This is only to be called manually using the Codea sidepanel while the debugger is active.

Module: AutoDoc

Generates HTML documentation for the current project.
AutoDoc (display)
Generates HTML documentation from the current project source and optionally displays it in a Fullscreen webview.

Parameters:

  • display (optional) Display a fullscreen webview and do not return to the caller.

Returns:

    HTML string

Usage:

  • -- Return the generated html to the caller
    local html = AutoDoc()
  • AutoDoc(true) -- This never returns 
Generated by Codea+ AutoDoc Last updated Tue May 17 09:13:58 2022