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

How to make a string in a table form?

Asked by
Arj783 72
4 years ago

If the title does not explain clearly enough, my doubt is this: How can (If we can) we convert a string into a table? For example, I have a string value. The string is "MyStringvalue". Keep in mind that it's the STRING, not the NAME OF THE STRING. So now, in my table, I want the first term in the table to be "M". The second is "y". Case sensitive. The third will be "S" and so forth. Is there a way we can do this? And if so, how?

1 answer

Log in to vote
2
Answered by
royaltoe 5144 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

There's a few ways of doing it:

approach one:

local myString = "Hello World"
local characters = {}

--putting string in table by looping through each position in the string
--and getting the substring at that position (the character at that position
for i = 1, #myString do 
    table.insert(characters, myString:sub(i,i))
end

--print out the characters array to show that we put the string in the table:
for _, character in pairs(characters)do
    print(character)
end

approach two:

--use string.split("") to split up every character and put it into a table
local myString = "Hello World"
local characters = myString:split("")

--print out the characters array to show that we put the string in the table:
for _, character in pairs(characters)do
    print(character)
end

Both ways work, but I prefer string.split(myString,"") (approach two) since it's faster to write out.

Both have same speeds really.

0
Good idea, I have lots of questions about strings! (Like "len", "lower", and more...) I will accept your answer for now! Have a great day :D Arj783 72 — 4y
0
Let me know what your questions are, I'd be happy to answer in discord since it's easier to talk there: Lucy#0003 royaltoe 5144 — 4y
Ad

Answer this question