Turning my string list into a table?

I have a string with a list of items set up like this:

Cats

Dogs

Ferrets

Keep in mind I’m separating the items by a new line character. The problem is, I need to take each item out of the list and put it into a table or something. E.g. {"Cats", "Dogs", "Ferrets"}. I’ve done some fooling around and I can’t seem to get this to work.

I’ve looked at these threads trying to figure out how to accomplish this:

How do you gmatch a string into a list?

They gave me a good starting point, but still no dice. Unfortunately I don’t have much experience with string manipulation like this so I’m kind of lost. Help?

In your current case, there are two ways you can search for these items you could either search for alphanumeric characters (%w) or non-new line characters ([^\n]), this would be an example for the former

local str = [[Cats

Dogs

Ferrets]]

for anim in str:gmatch("%w+") do
   print(anim,"hi")
end

The caveat to this is that it only finds alphanumeric (numbers + letters) characters in the string, while punctuations, and etc. are left out, if you wish to include those, conside this:

local str = [[Cats

Dogs

Ferrets]]

for anim in str:gmatch("[^\n]+") do
   print(anim,"hi")
end

If you want to learn more, i would strongly suggest checking out the lua users wiki or the lua pil.

String Library; Lua Users Wiki

lua “magic” characters

lua pil

1 Like

string.split is what you’re looking for.

If you wanted to split by newlines,

local stringsplitting = "line1\nline2\line3"
local list = stringsplitting:split"\n"
local function splitbynewline(str)
    return str:split"\n"
end
3 Likes
local str = [[
	Cats
	
	Dogs
	
	Ferrets
]]
local tab = {}
for w in str:gmatch('%a+') do
	tab[#tab + 1] = w
end
print(unpack(tab))

Cats Dogs Ferrets

You’re searching the string for every occurrence of the %a pattern, which represents an uppercase or lowercase letter. Then you add the + to capture the entire word. The string pattern reference page is very helpful for stuff like this

1 Like

This worked like a charm! Thanks to everyone who helped.