sctrcmp-like compare request

43 views
Skip to first unread message

Francisco Olarte

unread,
Oct 15, 2025, 4:46:57 AM (3 days ago) Oct 15
to lu...@googlegroups.com
Seeing a message about potential problems with strcoll in string compare I have noticed that < and <= over strings are not a strict order ( I think strict order is the term, comp-sci guys feel free to correct it ).

I mean using "null-aware strcoll" ( l_strcmp ) means (a<=b and b<=a) does not imply a==b, and conversely (not a<b and not b<a), as == is documented to be based on byte contents.

I realize it is too late for 5.5, and although it is trivial to do it in lua using string.byte() a strcmp-like ( null char aware ) function could be useful ( I mean, memcmp to the minimum of lengths, tie break using lengths ), something like:

-- Untested, just for exposition
-- Although not documented, assume it will continue casting to uchar before pushing.
local sbyte=string.byte
-- More or less what memcp does in c.
function memcmp(s1,s2,l) 
   for i=1 to l do
      local d = sbyte(s1,i)-sbyte(s2,i)
      if d~=0 return d end
   end
   -- return nil, never returns 0 for easier next.
end
function strcmp(s1,s2) 
  -- Checking they are both string left out.
  local l1,l2 = #l1,#l2
  -- memcmp common part, works with embededd nulls
  return memcmp(s1,s2,math.min(l1,l2)) 
  -- Tie break with length.
         or (l1-l2)
end

but coded in C could be useful as an addition to the string module. IMO it would be better to base <= and < on this, to make them coherent with == and move the strcoll stuff to a strcoll method, but it will break some existing code.

Francisco Olarte.
Reply all
Reply to author
Forward
0 new messages