I want to insert a string’s characters into a table, I discovered that using string.split , an array is created of the string’s characters (as it is separated by “,” by default).
Here is what I came up with :
local str = “abcd”
local cont = {}
local array = string.split(str)--it would be a,b,c,d right?
print(#array)--> 1 , why 1 ! isnt it supposed to separate a string?
for i = 1, #array do
cont[i] = array[i]
print(cont[2])--> nil,where I want it to print "b"
end
My alternative (still defunct) code :
for i = 1, #str do
cont[i] = string.split(str)[i]
print(cont[i])
end
Does someone know what the appropriate method to add all characters of a string into a table is?
string.split makes an array of the contents of the specified str delimited by , as default.
The str would have to contain a,b,c,d for you to get an array of size 4
You can simply use string.split(str, "") to achieve the exact result you’re looking for. The split function must split characters by a string, so supplying an empty string will split every character up (technically ""is between every character).
string.sub(str, Startingposition, Endingposition) so string.sub(“abcd”,1,1) would be a
atring.sub(“abcd”,2,2) would be b etc
Do some prints in the loop by setting a variable like
extractedCharacter = string.sub(“abcd”,1,1)
print(extractedCharacter)
table.insert(cont,extractedCharacter)
If you want to iterate over the contents of a string then you should use gmatch and search for matches of any one character as opposed to getting a substring at the start and end index of the same value. It’s much cleaner and proper.
local sepString = "abcd"
local content = {}
for letter in sepString:gmatch(".") do
table.insert(content, letter)
end
print(table.unpack(content)) -- a b c d
I am sorry but I am confused by that. I thought the gmatch pattern in your example would not find anything as there is not . in the string. Is the . special in some way?
Dot is a character class representative of any character (alphanumeric, symbol, anything). I don’t use it in a set, therefore the pattern specifies that any single found character is valid to be matched.
gmatch is a generator for a for loop. It allows me to run iterations for every match of whatever pattern I’ve specified.