lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Jeff Wise wrote:
Again, the data looks like '5A', nnnn, other data
Where the nnnn is a two byte signed integer (and hi-order byte, low-order
byte, not Intel format). For example, many length fields are X'2008' meaning 8200 bytes. The objective is to count these records. This is complicated by
the fact that the "other data" may contain '5A' bytes.

Personally I would just write a loop, something similar to: (completely untested)

function countrecs(str)
 local count, idx, len = 0, 1, #str
 while idx < len do
   count = count + 1
   assert(str:byte(idx) == 0x5A)
   idx = idx + (str:byte(idx+1)+str:byte(idx+2)*256)
 end
 return count
end

Searching for 0x5As won't help the case, so using byte / substr would be quicker then searching the string for them.

Alternatively, make the 0x5A an escape character. This would allow making the record header, for example, 5A00, and a true 5A could be 5A5A. This'd be more expensive when reading/outputing records, but would allow expansion to more special characters.

- Alex