[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Bug in 5.3 ipairs(), or feature?
- From: Jan Behrens <jbe-lua-l@...>
- Date: Wed, 4 Mar 2015 23:09:14 +0100
On Wed, 04 Mar 2015 11:13:50 -0500
Michael Welsh Duggan <mwd@cert.org> 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.
Neither a bug nor a feature. I would call it a "side-effect".
It's easily avoidable by doing something like this:
getmetatable("").__index = function(self, key)
if type(key) == "number" then
error("Tried to access numeric index of string")
else
return string[key]
end
end
This would be, however, less efficient than setting
getmetatable("").__index = string.
I think I have stumbled upon other cases where Lua has that sort of
"side-effects". While at first I found these side-effects annoying, I
meanwhile got used to them. IMHO they are a consequence of Lua's goal
to be simplistic.
>
> --
> Michael Welsh Duggan
> (mwd@cert.org)
Kind Regards
Jan Behrens
--
Public Software Group e. V.
Johannisstr. 12, 10117 Berlin, Germany
www.public-software-group.org
vorstand at public-software-group.org
eingetragen in das Vereinregister
des Amtsgerichtes Charlottenburg
Registernummer: VR 28873 B
Vorstände (einzelvertretungsberechtigt):
Jan Behrens
Axel Kistner
Andreas Nitsche
Björn Swierczek