lua-users home
lua-l archive

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



On Mar 24, 2014 6:34 PM, "Hisham" <h@hisham.hm> wrote:
>
> On 24 March 2014 10:47, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> >> Most common breakage seem to be (%d+) captures. [...]
> >
> > That is my experience too. (Not sure about the "most common", but sure
> > about a "quite common".)
>
> I just hacked together this super-ugly patch [1] (Roberto's patch plus
> a hack to make tonumber work) just to run the LuaRocks test suite with
> coercions off and see what happened.
>
> The results: it ran successfully! Looks like my strongly-typed brain
> hasn't failed me and I've been treating Lua as if it never had
> string-to-number coercions in the first place.
>
> I just checked the code and all my (%d+)'s were already religiously
> followed by uses of tonumber.
>
> If the addition of integers will make people review string conversions
> in their code anyway, perhaps now is a good time to at least deprecate
> automatic coercion, giving people a #define so they can test their
> code without it and prepare for the future.
>
> I haven't tried to run the LuaRocks testsuite with 5.3 yet because it
> uses a number of rockspecs which are not marked to be 5.3-compatible
> and therefore will fail with an "unsupported version" error message.
> Porting them all is a larger task.
>
> -- Hisham
> who really likes a disciplined, typed world
>
> [1] https://gist.github.com/hishamhm/9750528
>

I feel like format strings are one place where coercion is not a bad thing. It's all about making concise code that's easy to read and understand. When you write string.format("%d", x) it's clear that you intend x to represent a number, so having an implicit tonumber() around it makes sense. (Plus if x is, say, a table, an implicit conversion can throw an "expected number, got table" error,while if I'm remembering correctly tonumber(x) would return nil, making it harder to track down the bug.)

In fact I don't see why such coercion is a bad thing in most cases, since context usually exists. You know that the operands to + must be numbers and .. must be strings.