lua-users home
lua-l archive

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


On 19/09/2011 1.07, Patrick Donnelly wrote:
On Sun, Sep 18, 2011 at 10:21 AM, Gavin Wraith<gavin@wra1th.plus.com>  wrote:
In message<4E75EDC0.10400@interfree.it>  you wrote:

I still don't understand what's wrong in my reasoning, since the
implementation clearly proves me wrong as I showed in my first post.

-- Lorenzo

Consider these three snippets:
[...]


Evidently B uses one less instruction. In A the extra
instruction (LOADNIL) occurs outside the loop, in C within it.
So the ranking (<  means "better") appears to be B<  A<  C.
The key point, I think, is whether the local declaration is part
of an assignment.

This is a good summary. Another point neglected is that Lua recycles
slots in a function when a local goes out of scope. So if you have:

do
   local a = 1
   -- do something with a
end

do
   local a = 2
   -- do something with a
end

-- repeat above do<block>  end hundreds of times

In the above, you'd be ok with only 1 stack slots used (try it!). If
you try that without the do<block>  end, you have 200+ slots taken up
by the repeated 'a' locals.


Your reply and that of Gavin were really helpful.

I knew Lua had a ~200 limit for locals, but I thought it was per function. Now I learn it is per block. Useful info for code generation.


So, always put local declarations in the innermost block. It saves
stack space and is often faster. It just so happens it also helps with
readability :).


Yep! I was doing a stupid thing that in addition always triggered my internal "ugly-looking code detector" :-)

Now I'm happy twofold: I can avoid writing some stupid code and my code will look prettier too! :-D

Thanks again to You, Gavin and all the folks who cared to reply!


Cheers.
-- Lorenzo

P.S.: BTW Gavin has posted snippets of Lua 5.2 VM code, how is it possible? When I compiled Lua 5.2 beta with the standard makefile (mingw target on WinXP) it didn't build luac.exe. I thought it was because of the beta status, but maybe I'm missing something.