Hello!
2014-05-13 0:14 GMT-07:00 Eyas Guo:
> 这个代码
> local m, err = ngx.re.match("hello, 1234", "([0-9])|([a-z])")
> ngx.say('m=', #m)
> ngx.say('type=', type(m))
> ngx.say('m0=', m[0])
> ngx.say('m1=', m[1])
> ngx.say('m2=', m[2])
>
> 在ngx_lua-0.7.4输出是
> m=2
> type=table
> m0=h
> m1=nil
> m2=h
>
> 在lua-nginx-module-0.9.7输出是
> m=0
> type=table
> m0=h
> m1=nil
> m2=h
>
> #m的值不一样,这是为何?
>
这其实也是一个 FAQ 了。你得到的两个结果按照 Lua 5.1 语言标准的定义都是正确的,引用一下原文:
“The length of a table t is defined to be any integer index n such
that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n
can be zero. For a regular array, with non-nil values from 1 to a
given n, its length is exactly that n, the index of its last value. If
the array has "holes" (that is, nil values between other non-nil
values), then #t can be any of the indices that directly precedes a
nil value (that is, it may consider any such nil value as the end of
the array).”
更多细节请参见 http://www.lua.org/manual/5.1/manual.html#2.5.5
换句话说,#m 并不会给你期望的结果,因为 ngx.re.match 返回的 capture table 里会有 nil
空洞。我打算在未来的某个 ngx_lua 版本(也许是 0.10.0?)中把指示空分组的 nil 值给替换成 false,这样 #m
的返回值就会比较有意义了。
Regards,
-agentzh