Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

How to split string into chars and put them into array (list)?

Asked by
NorteX_tv 101
5 years ago
Edited 5 years ago

I want to create 1, specific string and then put them into the array like this:

local myString = "example string"

and then get in result:

local myList = {"e","x","a","m", etc. }

2 answers

Log in to vote
3
Answered by 5 years ago
Edited 5 years ago

you use string.gmatch() and use the "." string pattern, which is every character inside a string. then just literate over it and insert each character into a table.

local myString = "example string"
local myTable = {}

for character in string.gmatch(myString,".") do
    table.insert(myTable, character)
end

then if you want, you can literate over the table and print each character or value.

for _,v in pairs(myTable) do
    print(v) -- just prints the value or the character
end
  • e
  • x
  • a
  • m
  • p
  • l
  • e
  • s
  • t
  • r
  • i
  • n
  • g
0
Just in case for anyone who might not know what is gmatch, it returns an iterator function, kinda like how pairs returns next User#24403 69 — 5y
0
Thanks, very helpful. :D NorteX_tv 101 — 5y
Ad
Log in to vote
0
Answered by
nick540 20
5 years ago
Edited 5 years ago

This is easily done with just string.sub and a basic for loop.

function getChars(InputString)
    local ret = {}
    for local i = string.len(InputString), 1, -1 do -- For every character
        ret[i] = string.sub(InputString,_,_) -- Add this character to the table
    end
    return ret
end
0
why are you using _ User#24403 69 — 5y
0
^ You should only use _ if it's a value that won't be used. E.g for _, v in pairs. If you have no need for the index. turtle2004 167 — 5y
0
Thanks for help, I don't need it, as @up already did explain, but thanks for help, meaning is the most important. ;) NorteX_tv 101 — 5y
0
Changed it to not use _ nick540 20 — 5y

Answer this question