[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Number-to-string coercion gotcha (Was: Second return parameter from string.gsub is a gotcha)
- From: Dirk Laurie <dirk.laurie@...>
- Date: Sun, 30 Mar 2014 11:36:56 +0200
The original gotcha was that the code
package.searchpath (name, path:gsub("EXT",ext))
did not give the expected result, because the second return value
of gsub was interpreted as the optional third argument to searchpath.
The cause of the problem is not that gsub returns two values, or that
searchpath has optional extra arguments, but the feature we all love
to hate (or hate to love), automatic coercion.
The given values were:
path = "/home/dirk/test/EXT/?.EXT;./?.EXT"
name = 'lua53'
gsub does three substitutions and reports this as the number 3.
Automatic coercion turns that into the string "3", and since there
is no fourth argument to searchpath, the default is applied,
causing "lua53" to become "lua5/".
We are scrutinizing automatic string-to-number for possible deprecation,
but automatic number-to-string is not being reconsidered. I can see the
point of that in places like `..` and table.concat, and appreciate that,
as Roberto said, getting rid of coercion is not as straightforward as
But in the case of library functions whose inputs and outputs are in some
cases numbers and other cases strings, it seems to me that supplying
a number where a string is expected, or vice versa, is highly likely to be
an error. And here it is not a matter of digging deeply into lua_tolstring,
One could simply use different macros instead of luaL_checkstring
and luaL_optstring that would do a strict check on lua_type before
lua_tonumber or lua_tostring.