title: Compute the crc16 of a bytearray / userdata in lua
body: <p>I am writing a Wireshark protocol dissector in lua. The protocol it parses contains a crc16 checksum. The dissector should check whether the crc is correct.</p>
  
  <p>I have found a crc16 implementation written in C already with the lua wrapper code <a href="https://github.com/youlu-cn/luacrc16/blob/master/crc16.c" rel="nofollow noreferrer">here</a>. I have successfully compiled it and run it (e.g. <code>crc16.compute("test")</code>). The problem is it expects a string as input. From wireshark, I get a buffer that seems to be of lua type <code>userdata</code>. So when I do</p>
  
  <pre><code>crc16.compute(buffer(5, 19))
  </code></pre>
  
  <p>Lua complains <code>bad argument #1 to compute (string expected, got userdata)</code>.</p>
  
  <p><code>compute()</code> in the <a href="https://github.com/youlu-cn/luacrc16/blob/master/crc16.c" rel="nofollow noreferrer">crc16 implementation</a> looks like this:</p>
  
  <pre><code>static int compute(lua_State *L)
  {
      const char *data;
      size_t len = 0;
      unsigned short r, crc = 0;
  
      data = luaL_checklstring(L, 1, &amp;len);
  
      for ( ; len &gt; 0; len--)
      {
          r = (unsigned short)(crc &gt;&gt; 8);
          crc &lt;&lt;= 8;
          crc ^= crc_table[r ^ *data];
          data ++;
      }
  
      lua_pushinteger(L, crc);
          return 1;
  }
  </code></pre>
  
  <p>It seems <code>luaL_checklstring</code> fails. So I guess I would either need to convert the input into a lua string, which I am not sure it works, as not all bytes of my input are necessarily printable characters. Or I would need to adjust the above code so it accepts input of type userdata. I found <code>lua_touserdata()</code>, but this seems to return something like a pointer. So I would need a second argument for the length, right?</p>
  
  <p>I don't necessarily need to use this implementation. Any crc16 implementation for lua that accepts userdata would perfectly solve the problem.</p>