String sub isnt doing what its supposed to do

local mystring = "sjagui hsg hai gw shaighwa"

for i,char in mystring:split("") do
	if char ~= " " then
		mystring = string.sub(mystring, 1, i)
	end
end

print(mystring)

the i increases up until the last element in the array but when i try to use that variable to string sub the
mystring only stays at one character instead of going to the last

Issue was that in the loop, you were setting mystring = string.sub(mystring, 1, i) which sets mystring to “s” and then when you try to go through the loop again, the string it’s passing through string.sub is actually “s” and not the original string you need. You have to make another variable and make mystring just hold the original value so it can compare it to the new value in the loop.

code:

local mystring = "sjagui hsg hai gw shaighwa"
local stringClone = mystring

for i, char in mystring:split("") do
	if char ~= " " then
		print(stringClone)
		stringClone = string.sub(mystring, 1, i)
	end
end

print(stringClone)

Let me know if you have any questions :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.