<cache-return> cache returned values

xml namespace

Return a value from a cache, if it exists. Otherwise, execute the enclosed block.

This tag can be used to memoize a <macro> or other callable. Essentially, this means that if you call the macro a second time with the same parameters, it returns the previously calculated result. For macros that are slow to execute, this can result in significant speedups.

For example, the following code calculates the factorial of a number:

<moya xmlns="http://moyaproject.com"

    <macro docname="fact">
            <argument name="n"/>
        <cache-return key="n">
            <echo>calculating ${n}!</echo>
            <let f="1"/>
            <while test="n">
                <let f="f*n" n="n-1"/>
            <return value="f"/>

    <macro docname="main">
        <call macro="fact" let:n="7" dst="result"/>
        <call macro="fact" let:n="7" dst="result"/>
        <call macro="fact" let:n="7" dst="result"/>


If you run the above code, you will get the following output:

$ moya run cachereturn.xml
calculating 7!

The first time the fact macro is called, Moya displays "calculating 7!" in the terminal. The second and third time, the text is not displayed because the result is retrieved from the cache – without the need to execute the code within <cache-return>.

name purpose type required? default choices
cache Cache name text No "runtime"
for Time to cache for timespan No
key Cache key text No
keydata Cache data expression No None
local Should the value be cached for this tag only? boolean No yes
inherited attributes
name purpose type required? default choices
if Conditional expression expression No yes