I’m gonna necro this thread for something I’ve discovered to be quite useful in lua scripting that I want to share:

EDIT: I was wrong, as Trent pointed out below!

Here’s a stack overflow answer explaining:

Original post

When you’re writing a loop in which you set a callback, like so:

for i=1,16 do
  things[i].action = function()
     do_things_with(i)
  end
end

It’s very tempting to do what I did above and reference the loop index in the callback, and hope that the callback “closes over” its value so that each thing’s callback has a different index it works upon. It does not work that way. The reason is that there is one single loop variable, and its value changes with every iteration of the loop.

Instead, do this:

for i=1,16 do
  (function(i)
    things[i].action = function()
      do_things_with(i)
    end
  end)(i)
end

The extra layer of function which you call immediately below with the loop index traps the loop index and lets the inner callback “close over” it, preserving the value within the callback.

3 Likes