How to iterate individual characters in Lua string?

后端 未结 6 1419
陌清茗
陌清茗 2020-12-12 18:43

I have a string in Lua and want to iterate individual characters in it. But no code I\'ve tried works and the official manual only shows how to find and replace substrings :

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 19:07

    Iterating to construct a string and returning this string as a table with load()...

    itab=function(char)
    local result
    for i=1,#char do
     if i==1 then
      result=string.format('%s','{')
     end
    result=result..string.format('\'%s\'',char:sub(i,i))
     if i~=#char then
      result=result..string.format('%s',',')
     end
     if i==#char then
      result=result..string.format('%s','}')
     end
    end
     return load('return '..result)()
    end
    
    dump=function(dump)
    for key,value in pairs(dump) do
     io.write(string.format("%s=%s=%s\n",key,type(value),value))
    end
    end
    
    res=itab('KOYAANISQATSI')
    
    dump(res)
    

    Puts out...

    1=string=K
    2=string=O
    3=string=Y
    4=string=A
    5=string=A
    6=string=N
    7=string=I
    8=string=S
    9=string=Q
    10=string=A
    11=string=T
    12=string=S
    13=string=I
    

提交回复
热议问题