lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Considering that the discussion focusses on checking at compile time, why not move one step beyond and simply resolve it by static analysis. The compiler benefit would only be for dynamically loading code in your application like user scripts, plugins etc. and in those cases, with untrusted code, an extra local is the least of your worries.

ZeroBrane Studio code analysis does a good job at finding shadowing variable definitions (as well as unintended globals).

Other than that it is just discipline to make sure that large data structures are released early by assigning nil explicitly, or by using more do blocks so they automatically go out of scope.

Thijs


Sven Olsen <sven2718@gmail.com>schreef:

My point, however, was that the reuse of stack slots by the compiler involves more than just a quick check to see if the new local name matches any existing one at the same scope.

Yes, I think we're actually in agreement here.  While it's probably doable, a "strict locals" patch won't help programmers avoid most of the suboptimal code that involves memory needlessly trapped by local variables.  For example, consider:

function chunk()
  local a=big_table()
  do_something(a)
  do_something_else()
end

The problem here is that, if do_something_else() takes a while, and uses a lot of resources, a will still be hogging up memory while it runs -- Lua's only confident that it can release a after chunk() returns.

The fix is to wrap local a inside it's own block.  i.e.:

function chunk()
  do
    local a=big_table()
    do_something(a)
  end
  do_something_else()
end

(Now a can be freed before do_something_else() is called.)

So, while you could certainly hack together a "strict locals" patch, one that would do for locals about what strict.lua does for globals -- I'm not convinced it's a particularly good idea.  If the problem we're trying to fix is unnecessary memory use by locals, the solution is to use more do-blocks.  Enforcing naming discipline on locals is a mostly unrelated topic -- and most examples of local shadowing will happen inside nested blocks, a situation where they're not, actually, likely to be a source of memory inefficiencies.  

-Sven