尾随空参数 |
|
在我看来,lua 标准库应该清理掉,不要使用传递的参数数量来确定如何执行。
strfind(s,exp)
应该与 strfind(s,exp,nil,nil)
产生相同的结果。
然后你可以使用最大数量的参数为任何函数编写一个包装器。
function mystrfind(a,b,c,d) -- do some extra handling here... return strfind(a,b,c,d) end
示例(ReubenThomas 在 lua-l 列表上的邮件)
t = {} tinsert(t, 3, "hello", 1) print(t[3])
hello
时,我得到 1
。
tinsert(t, n, gsub(...))
现在我再次阅读它,我意识到这是尾随空值问题的反面 - lua 函数忽略额外的参数,而 c 函数获取所有参数(并且 tinsert 恰好插入其最后一个参数) - 也许最好将此页面命名为“由于 lua 函数和 c 函数对参数的不同处理而产生的问题” - PeterPrade
然而,在该线程的后面,当人们试图修复 tinsert 的奇异之处时,他们遇到了尾随空值问题 - 他们最终不得不意识到你无法用 lua 为 tinsert 编写一个合适的包装函数。让我引用 ET 在该线程中的最后一条消息
function tinsert(t, ...) if arg.n == 1 then %tinsert(t, arg[1]) elseif arg.n == 2 then %tinsert(t, arg[1], arg[2]) else error("wronger number of args ("..arg.n+1..") for tinsert"); end end
tinsert(t, foo())
--> 可能生成 tinsert(t,a,b)
tinsert(t, x, foo())
--> 可能生成 tinsert(t, x)
function readfrom(f) local h, err if f then h, err = %readfrom(f) else h, err = %readfrom() end ...
另一个例子出现在邮件列表中
> I just noticed that contrary to what you might expect, if you > pass "nil" as the fourth argument of strfind, it does a plain match. > Looking at the source, str_find indeed simply looks to see whether it > has a fourth argument. Sigh, another example of the arg handling ad hockery... > This is rather annoying, as in some other cases where it's nice to be > able to pass "nil" instead of omitting the argument. You say it... > It would not be contrary to the 4.0 manual to change this behaviour >[...] > Could this be done? Sure, it _could_. One could fix this place by converting the test lua_gettop(L)>3 to luaL_opt_int(L,3,0)==1, or one could finally start thinking about cleaning up argument handling in the C-API... >[...] is there any way around this? function strfind(a,b,c,d) c = c or 1 -- c has a similar problem... if d then return %strfind(a,b,c,d) else return %strfind(a,b,c) end end
在这里添加更多示例...