Search code examples
luaclosures

Do I need to create closures?


While I'm experienced in some other languages, I'm new to lua and find myself writing code like this:

  for k,v in pairs(config) do
    results[k] = nil
    table.insert(buttons, (function(k,v,results)
      return function()
        results[k] = v.button()
      end
    end)(k,v,results))
  end
  for k,v in pairs(config) do
    table.insert(breakers, (function(v)
      return function()
        v.breaker(_state)
      end
    end)(v))
  end
  for k,fn in pairs(tbl) do
    results[k] = nil;
    table.insert(wrappers, (function(k,fn,results)
      return function()
        results[k] = fn();
      end
    end)(k,fn,results));
  end

All the variables used in the closures are either local to the functions containing the for loop or are static globals.

Do I actually need to create closures like this in lua or am I just carrying baggage from my other language experiences?


Solution

  • It's not necessary, quote the original content in the reference manual:

    Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an upvalue, or external local variable, inside the inner function.

    for k,v in pairs(config) do
        results[k] = nil
        table.insert(buttons, function()
            results[k] = v.button()
        end)
    end