Closures/Value capture: Difference between revisions
Content added Content deleted
(These tasks, Multiple distinct objects and Closures/Value capture, have some similarities) |
(Lingo added) |
||
Line 1,023: | Line 1,023: | ||
</lang> |
</lang> |
||
=={{header|Lingo}}== |
|||
Lingo doesn't really support closures. But with the limitations described at [https://www.rosettacode.org/wiki/Function_composition#Lingo Function composition] and based on the fact that Lingo allows to create arbitrary code at runtime, the task can be solved like this: |
|||
<lang lingo>-- parent script "CallFunction" |
|||
property _code |
|||
on new (me, code) |
|||
me._code = code |
|||
return me |
|||
end |
|||
on call (me) |
|||
---------------------------------------- |
|||
-- If custom arguments were passed, evaluate them in the current context. |
|||
-- Note: in the code passed to the constructor they have to be specied as |
|||
-- arg[1], arg[2], ... |
|||
arg = [] |
|||
repeat with i = 3 to the paramCount |
|||
arg[i-2] = param(i) |
|||
end repeat |
|||
---------------------------------------- |
|||
res = VOID |
|||
do(me._code) |
|||
return res |
|||
end</lang> |
|||
<lang lingo>funcs = [] |
|||
repeat with i = 1 to 10 |
|||
code = "res="&i&"*"&i |
|||
funcs[i] = script("CallFunction").new(code) |
|||
end repeat |
|||
put call(funcs[3], _movie) |
|||
-- 9</lang> |
|||
Since the original task is a little trivial in terms of not depending on runtime arguments, here also a solution for an extended task: let each function[i] return the square of i plus the sum of all arguments passed to it at runtime: |
|||
<lang lingo>funcs = [] |
|||
repeat with i = 1 to 10 |
|||
code = "" |
|||
put "res = "&i&"*"&i &RETURN after code |
|||
put "repeat with i = 1 to arg.count" &RETURN after code |
|||
put " res = res + arg[i]" &RETURN after code |
|||
put "end repeat" &RETURN after code |
|||
funcs[i] = script("CallFunction").new(code) |
|||
end repeat |
|||
put call(funcs[3], _movie, 23) |
|||
-- 32 |
|||
put call(funcs[7], _movie, 4, 5, 6) |
|||
-- 64</lang> |
|||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |