Talk:Anonymous Functions: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Trappingnoobs
No edit summary
>NXTBoy
No edit summary
Line 1: Line 1:
"however this should be avoided in code that runs more than once." I'd never thought of that. So many of my scripts would, say, loop all the zombies in the game and connect events to them anonymously, whereas as you've pointed out there it'd've been much more efficient to point to a single function.<div style="border-top: 1px solid #AAA; color:#000000; font-size:10px">Trappingnoobs <span style="color:skyblue">(Writer)</span><span style="color:red"> Have I done something bad? Good? Tell me on my [[User_talk:Trappingnoobs|talk page]]</span><span style="color:grey;float:right">  21:46, 26 December 2011 (UTC)</span></div>
"however this should be avoided in code that runs more than once." I'd never thought of that. So many of my scripts would, say, loop all the zombies in the game and connect events to them anonymously, whereas as you've pointed out there it'd've been much more efficient to point to a single function.<div style="border-top: 1px solid #AAA; color:#000000; font-size:10px">Trappingnoobs <span style="color:skyblue">(Writer)</span><span style="color:red"> Have I done something bad? Good? Tell me on my [[User_talk:Trappingnoobs|talk page]]</span><span style="color:grey;float:right">  21:46, 26 December 2011 (UTC)</span></div>
:Yes, but normally you need an anonymous function to keep a closure on local variables:
: for _, zombie in ipairs(zombies) do
:    zombie.Torso.Touched:connect(function(by)
:        zombie.Head:remove() --You can still refer to zombie - not possible otherwise
:    end)
: end
:{{User:NXTBoy/sig|date=14:55, 27 December 2011 (UTC)}}

Revision as of 14:55, 27 December 2011

"however this should be avoided in code that runs more than once." I'd never thought of that. So many of my scripts would, say, loop all the zombies in the game and connect events to them anonymously, whereas as you've pointed out there it'd've been much more efficient to point to a single function.

Trappingnoobs (Writer) Have I done something bad? Good? Tell me on my talk page 21:46, 26 December 2011 (UTC)
Yes, but normally you need an anonymous function to keep a closure on local variables:
for _, zombie in ipairs(zombies) do
zombie.Torso.Touched:connect(function(by)
zombie.Head:remove() --You can still refer to zombie - not possible otherwise
end)
end
14:55, 27 December 2011 (UTC)