lua-users home
lua-l archive

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


Here's a personal story of mine where setfenv / getfenv saved my day.

A friend and I wrote this 3d game engine and we had to do a
presentation on a university project that we worked on for about 5
months - it's been an 3d world map editor for simulating town traffic.
The editor and the world loader (and a lot of other code) was written
in Lua (by us alone).
When preparing the presentation, I was torn between making a simple
powerpoint presentation or integrating a presentation into our 3d
engine.
What I finally did was, that I wrote a presentation software for the
3d engine very quickly (half an afternoon) that was able to show text
and pictures - so it was for me as good as powerpoint, so if my plan
would backfire, I could just go with screenshots instead of what my
plan was. Then I loaded the code of the editor (or parts of), and
faked all the required stuff through clever usage of function
environments. It worked like a charm and I went ahead. It hardly took
any time to do that.
The final result was quite impressive - as an opener it looked like
power point, but when I started on certain pages of the presentation
to rotate the view, inserting new objects or cars that would drive
around in the scenery that I built for the presentation, everyone was
surprised as noone would have expected that.

And it did not require me to rewrite the editor's source code - it was
just a few lines of code that made the job. I could even reload the
editor's sourcecode to do debugging in my presentation...
I have worked with OO and other stuff before that, but this kind of
flexibility, the ability to fake environments, that is in my opinion
an unmatched and extremely powerful feature of Lua. Of course - you
need to understand fully what you do and of course, if you apply it,
do it with great care. At best, don't use it at all, but it's good to
know it's there.
We used function environments later on in a few places where it was
important to sandbox the environment (running tutorial code for
example that needed to fit into a tutorial presentation framework) and
track what one's code does - without modifying the original code of
it.

Removing this functionality from Lua is in my opinion a step backward.
The purpose of this change seems to be to help "normal" people not to
be confused by the presence of two functions, but effectively, the
lack of this functionality is an ugly hindrance for clever people who
know what they are doing.

I really like Lua, but I was disappointed to see this change (without
a proper replacement). The 'in ... do ... end' syntax is a nice thing
- but in my opinion it doesn't fill the gap at all.