lua-users home
lua-l archive

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


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