Re: problems with the scoping in eu4
- Posted by jeremy (admin) Jan 09, 2011
- 1756 views
the use of with entry
The problem is highlighted by this code:
1 while f > 0 with entry do 2 integer sum = 0 3 ... 4 entry 5 f = ... 6 sum += 7 end while
It compiles because the reference to sum is in scope. It dies because line 2 has not been executed.
This is a coding error, somewhat like this:
integer sum if xyz > 1 then sum = 0 elsif xyz < -20 then sum = 100 end if sum += 1
If you understand with entry and have a valid use for it, then you will not have coding errors like you illustrate above. Your example above is misusing with entry and also not understanding how scoping works in Euphoria. The sum, in that case, even if it incremented, would always be reset to zero. The way to write your loop above is:
integer sum = 0 while f > 0 with entry do ... entry f = ... sum += end while
with entry is not for every loop, but many loops it makes the code cleaner, no duplication and thus easier to understand, less potential for initial bugs and for bugs due to later maintenance. For example:
public function find_all(object needle, sequence haystack, integer start=1) integer kx = 0 while start with entry do kx += 1 haystack[kx] = start start += 1 entry start = find(needle, haystack, start) end while haystack = remove( haystack, kx+1, length( haystack ) ) return haystack end function
Jeremy