How to iterate individual characters in Lua string?

后端 未结 6 1413
陌清茗
陌清茗 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条回答
  •  隐瞒了意图╮
    2020-12-12 19:31

    All people suggest a less optimal method

    Will be best:

        function chars(str)
            strc = {}
            for i = 1, #str do
                table.insert(strc, string.sub(str, i, i))
            end
            return strc
        end
    
        str = "Hello world!"
        char = chars(str)
        print("Char 2: "..char[2]) -- prints the char 'e'
        print("-------------------\n")
        for i = 1, #str do -- testing printing all the chars
            if (char[i] == " ") then
                print("Char "..i..": [[space]]")
            else
                print("Char "..i..": "..char[i])
            end
        end
    

提交回复
热议问题