Exception, why?

Hi everyone, I have this function, but every time I get an error. Why?

PushButton1.Action: TextArea1.Text = ConcCont(TextArea1.Text.ToText)

[code]Function ConcCont(t As Text) As Text
Using Xojo.Math

Const MAX_LENGTH = 248
Dim result() As Text
Dim pos, count As Integer
Dim rest As Integer = t.Length
Dim lines() As Text = t.Split(&uA)
Dim i As Integer
For Each line As Text In lines
	count = Min(MAX_LENGTH, line.Length)
	result.Append(If(i = 0, "NOTE ", "CONT ") + line.Mid(pos, count))
	rest = rest - count
	While rest > 0
		pos = pos + count
		count = Min(MAX_LENGTH, rest)
		result.Append("CONC " + line.Mid(pos, count)) // Exception, why?
		rest = rest - count
	i = i + 1
Return Text.Join(result, &uA)

End Function[/code]

Dim Result() As TextDim Pos, Count As Integer

Did you copy and paste?

What exception do you get?

[quote=322802:@Derk]Dim Result() As TextDim Pos, Count As Integer

Did you copy and paste?[/quote]
Sorry, now its correct, but this has nothing to do with the exception.


The Function should also add clean CONT Lines!

you get an exception because pos and/or pos+count is out of bounds of the length of your text.

Thanks. How to fix it?

since you’re getting an out of bounds exception on

			result.Append("CONC " + line.Mid(pos, count)) // Exception, why?

there are only 2 choices

  1. result.Append is causing it (which is not likely)
  2. line.mid is causing it

You can figure out which by

  1. breaking this into 2 lines
 		dim tmp as string = "CONC " + line.Mid(pos, count)
		result.Append tmp

and running
Now you’ll see which portion of that line is the problem

And you’ll find that MID is causing it

Mid(start As Integer) As Text
An overload of Mid that returns all of the characters from start to the end of the text. The start position is a zero-based.

Dont call mid when the start position is > the number of characters
The new framework throws exceptions when you do this

Read the docs about TEXT.MID and I’m sure you will sort out how to fix this

Pos has to be set to 0 at the beginning of the loop, and it is advisable to iterate in a for … next loop instead of for each … See the warning about for each iterations and index order at http://developer.xojo.com/for-each-next (although currently it will probably work alright).

Also, better compare the length of each line and not against t.length as the sum of all lines.lenghts will differ from the original (the EOLs are stripped).