Search code examples
luawiresharkstring-conversion

Conversion of sequence of bytes to ASCII string in lua


I am trying to write custom dissector for Wireshark, which will change byte/hex output to ASCII string.

I was able to write the body of this dissector and it works. My only problem is conversion of this data to ASCII string.

Wireshark declares this data to be sequence of bytes. To Lua the data type is userdata (tested using type(data)). If I simply convert it to string using tostring(data) my dissector returns 24:50:48, which is the exact hex representation of bytes in an array.

Is there any way to directly convert this byte sequence to ascii, or can you help me convert this colon separated string to ascii string? I am totally new to Lua. I've tried something like split(tostring(data),":") but this returns Lua Error: attempt to call global 'split' (a nil value)


Using Jakuje's answer I was able to create something like this:

function isempty(s)
  return s == nil or s == ''
end
data = "24:50:48:49:4A"
s = ""
for i in string.gmatch(data, "[^:]*") do
    if not isempty( i ) then
        print(string.char(tonumber(i,16)))
        s = s .. string.char(tonumber(i,16))
    end
end
print( s )

I am not sure if this is effective, but at least it works ;)


Solution

  • There is no such function as split in Lua (consulting reference manual is a good start). You should use probably string.gmatch function as described on wiki:

    data = "24:50:48"
    for i in string.gmatch(data, "[^:]*") do
      print(i)
    end
    

    (live example)

    Further you are searching for string.char function to convert bytes to ascii char.