string.bytes

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

string.bytes

Dirk Laurie-2
By analogy to the function utf8.codes, it would be nice to have a
function string.bytes so that the construction

     for p, c in string.bytes(s) do body end

will iterate over all bytes in string s, with p being the position.
This is surprisingly clumsy in pure Lua, unless I am missing a trick.
Of course, if the string is pure ASCII, utf8.codes will do the trick.

Reply | Threaded
Open this post in threaded view
|

Re: string.bytes

Javier Guerra Giraldez
On Fri, 12 Apr 2019 at 10:08, Dirk Laurie <[hidden email]> wrote:
>
> By analogy to the function utf8.codes, it would be nice to have a
> function string.bytes so that the construction
>
>      for p, c in string.bytes(s) do body end
>
> will iterate over all bytes in string s, with p being the position.
> This is surprisingly clumsy in pure Lua, unless I am missing a trick.

I usually do

for i = 1, #s do
   local c = s:byte(i)
   ..... body....
end


not as neat as a real iterator but can't complain on readability


--
Javier

Reply | Threaded
Open this post in threaded view
|

Re: string.bytes

Dennis Fischer
It's not hard to just implement it yourself though

local bytes do
 function iter(str, pos)
  if pos <= #str then
   return pos+1, str:byte(pos, pos)
  end
 end
 function bytes(str)
  return iter, str, 1
 end
end

There, an iterator over all the bytes in a string and their corresponding position 😉