问题
In Ant-contrib, we can do something like:
<for list="a,b,c,d" param="instence">
But if I don't have a list, I only have a limit, e.g. limit=4.
Is there a way to do for loop based on limit, like:
<for limit="4" param="index">
回答1:
The Ant addon Flaka provides some solutions for your problem.
1) Use a while loop
the test attribute evaluates some EL expression,
which maybe a simple counter, f.e.
<project name="demo" xmlns:fl="antlib:it.haefelinger.flaka">
<!-- some counter -->
<fl:let>
countdown = 3
</fl:let>
<fl:while test=" countdown >= 0 ">
<fl:echo>
#{countdown > 0 ? countdown : 'bang!' }..
</fl:echo>
<fl:let>
countdown = countdown - 1
</fl:let>
</fl:while>
</project>
output:
[fl:echo] 3..
[fl:echo] 2..
[fl:echo] 1..
[fl:echo] bang!..
or some other expression, f.e. checking for existence of a file, means looping until some file exists :
<fl:while test=" !'/home/rosebud/stop'.tofile.isfile ">
<fl:echo>
still working..
</fl:echo>
</fl:while>
2) Use a for loop with break or continue :
<project name="demo" xmlns:fl="antlib:it.haefelinger.flaka">
<fl:for var="i" in=" list(1,2,3,4,5,6) ">
<fl:echo>i = #{i}</fl:echo>
<fl:break test=" i == 3 " />
</fl:for>
<fl:for var="i" in=" list(1,2,3,4,5,6) ">
<fl:continue test=" i > 3 " />
<fl:echo>i = #{i}</fl:echo>
</fl:for>
</project>
which gives the same result :
[fl:echo] i = 1
[fl:echo] i = 2
[fl:echo] i = 3
See more details in the Flaka manual
回答2:
<project name="Attachments" default="print">
<property name="numAttachments" value="20" />
<target name="generate">
<script language="javascript"><![CDATA[
var list = '1';
var limit = project.getProperty( "numAttachments" );
for (var i=2;i<limit;i++)
{
list = list + ',' + i;
}
project.setNewProperty("list", list);
]]>
</script>
</target>
<target name="print" depends="generate">
<for list="${list}" param="letter">
<sequential>
<echo>Letter @{letter}</echo>
</sequential>
</for>
</target>
</project>
回答3:
Its not exactly what you want, but this page has an example. Essentially, you pass in the limit as a list of numbers. Its not elegant, but it works.
Here's another idea - see the answer by user "cn1h". Its a cool way to get around limitations in ANT - embed a script from another language which can do what you want. Nice!
回答4:
In antcontrib you can also do:
<for param="index" end="@{numberOfIterations}" start="1">
But be aware of a bug: It is unable to handle begin and end being the same. So when "numberOfIterations" equals 1 you get an error.
We got a workaround for this, checking the value of numberOfIterations first and only when its not 1 doing the for-statement.
<if><equals arg1="1" arg2="@{numberOfIterations}"/>
<then>
....
</then>
<else>
<for param="index" end="@{numberOfIterations}" start="1">
....
</else>
</if>
来源:https://stackoverflow.com/questions/7655735/how-to-do-for-loop-based-on-a-limit-in-ant