Hands-On Usage
for_each_loop is best suited for scenarios where you need to sequentially perform operations on each element in an array—for example, iterating through an array storing multiple State IDs to build improvements one by one, or adding modifiers to dynamically stored country tags. Compared to manually expanding logic, it keeps batch array processing code clean and maintainable.
# Example: Iterate through an array storing state victory points and set them one by one
set_temp_variable = { my_array^0 = 3 }
set_temp_variable = { my_array^1 = 7 }
set_temp_variable = { my_array^2 = 15 }
for_each_loop = {
array = my_array
value = v # Current element value stored in v
index = i # Current index stored in i
# Perform operations on v here, such as logging or conditional checks followed by break
if = {
limit = { check_variable = { v = 7 } }
set_temp_variable = { break = 1 } # Exit early after finding target value
}
}
Synergy
[add_to_temp_array](/wiki/effect/add_to_temp_array) / [add_to_array](/wiki/effect/add_to_array): Populate the array before loop execution so for_each_loop has elements to iterate over; these form a classic "prepare-consume" partnership.
[if](/wiki/effect/if): Use if within the loop body to perform conditional checks on the current element v, enabling filtering logic that "only executes effects on elements meeting the condition."
[find_highest_in_array](/wiki/effect/find_highest_in_array) / [find_lowest_in_array](/wiki/effect/find_lowest_in_array): Use these commands first to locate extrema, then combine with break inside for_each_loop to exit early and avoid unnecessary full traversals.
[set_temp_variable](/wiki/effect/set_temp_variable): Frequently needed within the loop body to write intermediate calculation results or accumulated values back to temp variables for use by subsequent logic.
Common Pitfalls
- Forgetting to manually reset the
break variable: The default break variable name is break, but if something earlier set it to a non-zero value, the loop will exit immediately upon entry without executing any effects. Make it a habit to explicitly reset with set_temp_variable = { break = 0 } before the loop, or use a custom name to avoid naming collisions.
- Treating
for_each_loop as a scope switcher: The scope within the loop body remains the scope you entered with; v and i are just ordinary temp variables (numeric values) and cannot be directly used as country/state scopes to invoke scope-dependent commands. If you need to perform scope-level operations on stored tags or state IDs, pair it with dedicated commands like random_scope_in_array or for_each_scope_loop.