Wireshark-dev: Re: [Wireshark-dev] accessing multiple occurrences of the same field with lua

From: Hadriel Kaplan <HKaplan@xxxxxxxxxxxxxx>
Date: Fri, 8 Mar 2013 21:15:53 +0000
On Mar 8, 2013, at 6:40 AM, Cristian Constantin <const.crist@xxxxxxxxxxxxxx> wrote:

> cristian: thanks a lot tony and hadriel. it works. otoh I need to dive
> a little bit more into this lua language.
> 
> one more thing though. suppose I do this in the tap.packet():
> 
> local tags = { m3ua_param_tag() }
> for i,t in ipairs( tags ) do
>        print("tag no:", i, "tag type:", t, tonumber(t));
>        local t_no_space = string.gsub(tostring(t), "%s*(%w+)%s*", "%1")
>        print("tag type:", t_no_space, tonumber(t_no_space));
> end
> 
> the output looks like this:
> 
> tag no: 1       tag type:       512     nil
> tag type:       512     512
> 
> why are there TABS (!!) in the string representation of t, i??

Because you're using "," in your Lua print() function, which means each thing in it is a separate argument to the function call, just like in C functions.  It's just that Lua's print function writes to stdout each argument separated by a TAB.  I.e., you're not doing 'print(foo)', but rather 'print(foo, bar, pie)', and print is doing what it does for each argument.

If you want them written out without that TAB, only pass it one argument: a string made up of your separate pieces.

So like this:
    print("tag no: " .. i .. ", tag value: " .. tostring(t))

The ".." is a concatenation operator in Lua, so it's concatenating those separate things into one string, which is the one argument being given to print().


> tonumber() won't work on t,i as they are, returning "nil"...
> it works after removing them with the string pattern match/replace.
> 

The reason you're getting nil is because you're calling 'tonumber(t)', which means you're trying to convert whatever 't' is into a Lua number.  But 't' isn't a string or number that can be converted into a number; it's a FieldInfo object.  So tonumber() returns nothing, and print() writes that as 'nil'.  Your string pattern match/replace works because you've converted the FieldInfo into a string when you did 'tostring(t)' - you don't even need to do the pattern replacement (the string.gsub()) at that point, because what makes it work is converting a FieldInfo object into a Lua string, and tonumber() can handle converting a string into a number.

So you could have done this:
    print("tag type:", t_no_space, tonumber(tostring(t)))

But there's no real point in doing that - because print() is just going to convert the number generated by tonumber() right back into a string it can print out.  So might as well skip the step of converting a object into a string into a number into a string - just convert the object into a string.

So again, just do this:
    print("tag no: " .. i .. ", tag value: " .. tostring(t))


-hadriel