Foreach

From Mario Fan Games Galaxy Wiki
Revision as of 19:23, 12 February 2009 by Xgoff (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A foreach (or for each) loop is a loop that iterates through a collection, whether it be values, strings, or some form of objects. In many cases, a foreach loop is just a for loop with extra syntax, but some languages have an explicit foreach keyword. Unlike for loops, foreach loops usually do not take a starting index, comparison expression, and increment amount; this information is implied by the structure of the collection itself.

Click

Currently, in MMF/TGF, there is no foreach function, nor do fastloops even provide syntax for it. However, it is still possible to emulate the behavior by using a fastloop in conjunction with Spread Value:

Start of Frame
--> ObjectA - Spread Value in ID (AV A): 0

Always
--> Start Loop: "foreach_ObjectA"; NObjects("Object A")

On loop "foreach_ObjectA"
+ ID of "ObjectA" = loopindex("foreach_ObjectA")
+ [other conditions to apply to this instance]
--> [do whatever]

Lua

Again, Lua does not have an explicit foreach keyword, but it has two functions that can be used with for to provide the functionality: pairs() and ipairs(). Both of these take the table to traverse as their only argument. pairs iterates through all table keys regardless of type, while ipairs only iterates through integer keys.

_table_ = { 1, 2, 3, 4, ["hello"] = 5, ["what"] = 6, 7, 8}
for k, v in pairs(_table_) do
    print(k, v)
end

for k, v in ipairs(_table_) do
    print(k, v)
end

Python