Closures/Value capture: Difference between revisions
Content added Content deleted
(Added FreeBASIC) |
|||
Line 614: | Line 614: | ||
100 |
100 |
||
ok |
ok |
||
</pre> |
|||
=={{header|FreeBASIC}}== |
|||
FreeBASIC doesn't support closures or anonymous methods, as such. However, what we can do is to create an array of objects to capture their index and then call a method on those objects which squares the index. This approach is similar to how some other object oriented languages implement closures 'under the hood'. |
|||
<lang freebasic>' FB 1.05.0 Win64 |
|||
Type Closure |
|||
Private: |
|||
index As Integer |
|||
Public: |
|||
Declare Constructor(index As Integer = 0) |
|||
Declare Function Square As Integer |
|||
End Type |
|||
Constructor Closure(index As Integer = 0) |
|||
This.index = index |
|||
End Constructor |
|||
Function Closure.Square As Integer |
|||
Return index * index |
|||
End Function |
|||
Dim a(1 To 10) As Closure |
|||
' create Closure objects which capture their index |
|||
For i As Integer = 1 To 10 |
|||
a(i) = Closure(i) |
|||
Next |
|||
' call the Square method on all but the last object |
|||
For i As Integer = 1 to 9 |
|||
Print a(i).Square |
|||
Next |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</lang> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
</pre> |
</pre> |
||