lua-users home
lua-l archive

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

On Wed, Nov 27, 2013 at 4:11 PM, Philipp Janda <> wrote:
I disagree. The numeric for loop is a second class citizen: you can't pass it to (or return it from) a function (which sadly is still not being done very often in the Lua code I've seen -- the recently released lua-fun being a notable exception). Whenever you pass a table as input to a function, consider passing an iterator triplet instead. This way you can use the function for `pairs()`, `ipairs()`, `filter(p ,pairs())`, map(f, ipairs())`, and possibly other data sources. At some point in the future I'd like to see a merge of iterators and LTN12 sources and sinks.

This could be very interesting. I just wish iterators were easier to create. I can still never quite remember how they work and end up looking at previous implementations for reference (or just using ipairs and filtering in the loop).

I don't think passing an iterator instead of an array is suitable 100% of the time (sometimes you need to access arbitrary elements at random), but when you are planning to iterate, it would be a good idea to accept either a table to iterate through (using some default method such as ipairs) or an iterator function. In fact, I use a similar pattern already for functions that take long strings as input: they can accept a file handle (will read from the current position to EOF), a string (will read the entire string), or a function (will call when more data is needed, usually passing some parameter such as the position we want to read and/or the number of bytes we want).

Again I find myself often wishing for an is_indexable() and is_callable() so that I could just accept any object (table, function, userdata) and not have to explicitly check types. I'm a big fan of duck typing. Even better if the C API supported similar. It's already partway there with strings: lua_tostring() and lua_tonumber() both accept numbers and strings, and lua_isnumber() and lua_isstring() both check for both types; lua_type() must be used if for some reason you want to differentiate between the two. It'd be great if lua_is* and lua_to* in general honoured metamethods. I'd also been bitten before by the C API not accepting a table with a __tostring metamethod as a string. (Was that changed in 5.2?)

btw, I very much like the idea of moving most "table" functions to an "array" library (not "list" because that brings linked lists to mind) and making some distinction between the two. Treat "array" as a special case of "table" - a table in which all integer elements range from 1 to n with no gaps. (Or from 1 to self.n with possible gaps?)

Sent from my Game Boy.