Splitting a string

Okay, this has annoyed me for a while. You see, DLabels do not automatically add newlines when you’re out of space. Instead they just get truncated. This means I have to find the last whitespace character in a string of the twenty first characters of the original one. How would I do this?

[editline]09:18PM[/editline]

Also, I do not feel this is a newbie question. I’m asking for an effective way to to it, of course I could do it ineffectively, too :stuck_out_tongue:

[editline]09:46PM[/editline]

Never mind, this code fixed it: [lua]string.gsub( string.Left( question, 20 ), “.+[%s].+”, "%1
" … string.sub( question, 21 ) )[/lua]

[editline]09:53PM[/editline]

Could you instead tell me, what’s wrong with [lua]–TODO: FIX THIS
local n = 1

		while string.len( string.sub( self.question, 0 + ( 20 * ( n - 1 ) ), -1 ) ) > ( 20 * n ) do
			self.question = string.gsub( string.Left( question, 20 * n ), ".+[%s].+", "%1

" … string.sub( question, ( 20 * n ) + 1 ) )
n = n + 1
end[/lua] ?

Error message?

you don’t appear to have defined ‘question’. Did you perhaps mean ‘self.question’?

Just a suggestion, use a for-loop:



for n = 1, string.len( string.sub( self.question, 0 + ( 20 * ( n - 1 ) ), -1 ) ) do
	self.question = string.gsub( string.Left( question, 20 * n ), ".+[%s].+", "%1
" .. string.sub( question, ( 20 * n ) + 1 ) )
end

Don’t know if it’ll fix your problem, though. It’s better to use over a while when you can.

Thanks! It’s nice to get answers, even though I fixed this already in quite a hacky way… What I did was:
-Take the first 20 characters of the string
-Put the new string in a table
-Create a new string from all but the 20 first characters of the string
-Repeat the above process until the whole string is contained in the table
-Find the last whitespace characters in the strings
-Replace them with newline characters
-Concatenate the string

Behold:
[lua] --Somewhat fixed :stuck_out_tongue:

		local str = self.question
		local tbl = {}

		table.insert( tbl, string.Left( str, 20 ) )
		str = string.sub( str, 21, -1 )
		
		while ( string.len( str ) > 20 ) do
		
			table.insert( tbl, string.Left( str, 20 ) )
			str = string.sub( str, 21, -1 )
		
		end
		
		table.insert( tbl, string.Left( str, 20 ) )
		
		for _, v in ipairs( tbl ) do
		
			v = string.gsub( v, ".+[%s].+", "%1" )
		
		end
		
		self.question = string.Trim( string.Implode( "

", tbl ) )
[/lua]