lua-users home
lua-l archive

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

On Friday, July 5, 2013, Mark Hamburg wrote:
Fixing the "problem" with an ax. Just come out and say that Lua doesn't have arrays. Get rid of ipairs. Get rid of #. Get rid of table.insert, etc.

If you want to iterate an array-like table use:

    for i = 1, n do
        local v = t[ i ]
        -- process entry i with value v

It's your problem to figure out n.

This solution is, of course, trivial to implement. Arguably, you have it today since it just avoids use  or some features.

But it is also a pain. How do we find n above? One answer is maxn. If we are going to iterate the whole array, this doesn't make the time complexity any worse.

What this won't handle and is where the generic encoding solutions may run into trouble is not holes in the middle but holes at the end.

To resolve that, we can introduce a magic value and then bring # and ipairs back provided that one understands the need to either not have holes or to use the magic value to have them work "correctly".

Or we can introduce an array module that gives us a structure with the desired semantics.

The latter seems cleaner. I would probably resist bringing back ipairs on the basis that it is only sensible for arrays and hence should be array.ipairs. The argument for the length operator is probably one of efficiency of execution and notation, but I'm not fully sold on it. (They can come back/stay but they would probably exist under a compatibility switch.)

Simple but also arguably dramatic in a way that isn't necessarily warranted.

Finally, one addition in support of any of these answers that might be good is a __type fast metatable field that type would check with rawtype taking over type’s current role. That way, one could check to see whether something was really an array as opposed to just a table (or a userdata depending n implementation).


Personally, after reading this and Jay's post...

You guy's are right. Lua is fine. My passion has subsided and reason is back in control. :)

FWIW: Monkey patching `type` so that it outputs:

[base_type], [the string value at metafield "__type" or the return value from function call at "__type"] something that I do all of the time. It was the basis for my earlier suggestion. 

It works pretty well for me and the fact that I have to patch it to do it that way is also fine. It just means that I also need to adapt other libraries that do similar things (Penlight) to the same convention. That's just kind of "how it is in Lua."

-- Andrew