lua-users home
lua-l archive

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


A comparison like "string1 < string2" is very common in sorting. If
you want to consider their numeric values, you should, as the OP
stated, convert them to numbers.

One thing I've wondered though is why the C API functions don't do
coercion. I made a patch to change that, but I'm wondering what the
rationale was for it not to be default behaviour. My localization
system relies on the __tostring metamethod and it's much easier not to
have to stick a tostring(foo) in every call to C library functions.

On Wed, Apr 21, 2010 at 15:17, Matthew Wild <mwild1@gmail.com> wrote:
> Excerpts from Stuart P. Bentley's message of Tue Apr 20 14:41:00 +0100 2010:
>> One case where I've actually encountered unavoidable issues with a Lua
>> design due to type coercion was something like this, if I recall correctly:
>>
>> num_table{[2]="This gets printed instead"}
>>
>> index_searched_for="2"
>>
>> print(num_table[index_searched_for] or "Even though this is what should be
>> printed!")
>>
>
> Lua 5.1:
>
>  > num_table = {[2]="This gets printed instead"}
>  > index_searched_for="2"
>  > print(num_table[index_searched_for] or "Even though this is what should be
>   printed!")
>  Even though this is what should be printed!
>
> Lua generally doesn't do coercion as a rule (compared to some languages, such
> as PHP). It generally only coerces numbers<>strings when doing direct
> comparisons (that otherwise wouldn't make sense) or a function indicates (by
> using tostring/lua_tostring) that it is expecting a string, and the user
> passed a number (or vice-versa). Table indexing *never* employs coercion,
> which I agree would be most awkard.
>
> There is a case for removing what coercion there is, throwing errors in these
> cases, and forcing people to be more explicit. However as stated elsewhere in
> this thread I don't think that would necessarily be a valuable move.
>
> Matthew
>



-- 
Sent from my toaster.