Closures/Value capture: Difference between revisions
Content added Content deleted
(Fixed code to not use wrong variable capturing that got hidden by looping again using that variable.) |
|||
Line 399: | Line 399: | ||
type |
type |
||
TFuncIntResult = reference to function |
TFuncIntResult = reference to function: Integer; |
||
// use function that returns anonymous method to avoid capturing the loop variable |
|||
⚫ | |||
function CreateFunc(i: Integer): TFuncIntResult; |
|||
begin |
|||
⚫ | |||
Result := |
|||
function: Integer |
|||
begin |
|||
Result := i * i; |
|||
end; |
|||
end; |
|||
⚫ | |||
Funcs: array[0..9] of TFuncIntResult; |
|||
⚫ | |||
begin |
begin |
||
// |
// create 10 anonymous functions |
||
for i := Low(Funcs) to High(Funcs) do |
for i := Low(Funcs) to High(Funcs) do |
||
Funcs[i] := |
Funcs[i] := CreateFunc(i); |
||
// call all 10 functions |
// call all 10 functions |
||
for i := Low(Funcs) to High(Funcs) do |
for i := Low(Funcs) to High(Funcs) do |
||
Writeln(Funcs[i]()); |
|||
end.</lang> |
end.</lang> |
||
{{out}} |
{{out}} |