How do I iterate over characters in a string?

292 views Asked by At

In moonscript, how can I iterate over characters in a string?

I tried iterating as if the string was a table, but that did not work:

s = "hello"
for c in *s
  print c
1

There are 1 answers

0
congusbongus On

Following lua equivalents:

Iterate by index and substring

s = "hello"
for i = 1, #s
  print s\sub(i, i)

Iterate using pattern matching

s = "hello"
for c in s\gmatch"."
  print c

For unicode strings, you can use:

s = "✅✈♛"
for _, c in utf8.codes(s)
  print utf8.char(c)