Althought I stated that my string is "name1 name2 name3 name4 name5", I don't actually know my string and want a way to apply this to any string. "this" being a way to cut a string with words separated by a space into different variables.

1 Answer

You can use string.gmatch to get each word by using a pattern that describes one or more non-whitespace characters "%S" and add them into a table.

local text = "name1 name2 name3 name4 name5" local words = {} for word in text:gmatch("%S+") do table.insert(words, word) end local variable1, variable2, variable3, variable4, variable5 = table.unpack(words) 

I wouldn't recommend using the last line as you can simply address the words through their table index. Having variable names for every single word is not practical for high or unknown numbers of words.

So just use words[5] instead of variable5 in your example

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.