lua-users home
lua-l archive

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


Soni L. <fakedme@gmail.com> writes:

> On 04/03/15 01:13 PM, Michael Welsh Duggan wrote:
>> In Lua 5.2, ipairs() on any non-table (or table-like) type would throw
>> an error.  In 5.3, ipairs("foo") or ipairs(nil) returns a valid iterator
>> function, as long as LUA_COMPAT_IPAIRS isn't turned on.  (It is turned
>> on by LUA_COMPAT_5_2, which is the default in the base release.)
>>
>> For nil, I get something useful on iteration:
>>
>>    > for i, v in ipairs(nil) do print(i, v) end
>>    stdin:1: bad argument #1 to 'for iterator' (table expected, got nil)
>>    stack traceback:
>>            [C]: in function 'for iterator'
>>            stdin:1: in main chunk
>>            [C]: in ?
>>
>> But for a string I get, unexpectedly, nothing.
>>
>>    > for i, v in ipairs("foo") do print (i, v) end
>>    >
>>
>> So...  Bug, or feature?  I vote bug, if for no other reason than the
>> inconsistent behavior.
>>
> The string metatable has __index which is an empty sequence.

Ugh!  That makes sense.  This is, however, completely unexpected
behavior.  Context: I had a function that accepted a sequence of strings
and used ipairs on it to do its work.  Someone called the function with
a single string.  Instead of getting an error, they got an unexpected
"empty" result.  I don't recall if I tested that this errored in the
past when we were using 5.2, but this ended up being a very confusing
result.  I would argue that this problem should be documented under
ipairs(), if only because the result is so unexpected.

Of course, the counter-argument is that I should always be testing for
argument types up front rather than expecting things to fail during
normal processing.  I would have to accept that argument.

-- 
Michael Welsh Duggan
(mwd@cert.org)