lua-users home
lua-l archive

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


On 7/7/2016 4:05 PM, William Ahern wrote:
On Fri, Jul 08, 2016 at 12:36:30AM +0200, Dirk Laurie wrote:
Suppose that t represents the rooms in an hotel. Guests arrive
and leave. You evaluate #t. It tells you where to find an empty
room. You put a guest in that room. Next guest comes. Again
#t finds an empty room. Why is it bad if that room happens to
have a lower number? But it would be bad if the guarantee
that t[#t+1] is empty did not hold.

So you've put them in the room. Then what? You can't find them again. You
can't do `for i=1,#t do ... end` and expect to find them.

But what if you don't need to remember. In the hotel case, once they have a key and are in a room, for the most part the rest of the hotel only cares if that room is occupied (clean it during the day, don't assign another guest to it, etc.) or not.

Besides, the hotel is itself a fixed size array of floors (often with 13 missing aka nil) each containing a fixed array of rooms. Extending a hotel is a big deal, involving lots of money and other resources, and mediated by building permits and inspections.

So iterating over all rooms is already an O(n) task, and normally doesn't stumble over the missing 13th floor.

You could remember the index somewhere, but then you've only created a level
of indirection. Wherever you store the index you could have kept the object
itself. You if you wanted to anchor the object in memory, it would be
simpler and more performant to store it as the key.

Hmmmm... I guess one use would be for implementating luaL_ref. I'm not sure
how useful that would be in Lua code. Maybe I just need to think about it
longer.

IIRC, that is exactly how luaL_ref() was implemented. At least in a high-order pseudo-code description. The integer returned is used to look up the saved object, and needed to be something (like an integer) that would be easy to return to C code as plain data. Using #t+1 to get it is cheap, easy, and reliable. And looking it up later is also cheap and easy.

I'd hate to see that feature of # on a plain table be lost.

--
Ross Berteig                               Ross@CheshireEng.com
Cheshire Engineering Corp.           http://www.CheshireEng.com/
+1 626 303 1602