Get Line number From CursorPosition

I’ve been staring at my code for a while and I haven’t slept so I’m really tired.
I’m trying to write a function that returns the line number that the cursor position is on.

Example:
image The cursor is on line 321

function getLineFromCursorPosition()
	local lines = string.split(TextBox.Text,'\n')
	local totalChars = 0
	warn(TextBox.CursorPosition)
	for i,v in ipairs(lines) do
		print(v)
		totalChars+=string.len(v)
		if totalChars >= TextBox.CursorPosition then
			return i
		end
	end
	return -1
end

I’m going to sleep. I’ll look at this riddle later with a fresh pair of eyes. :woozy_face:
If anyone wants to help me out in the meantime, I’d appreciate some input as to what I’m doing wrong.

Can you show us the output you’re getting?

Also I don’t think += works in lua, you’d have to write that line like this:

totalChars = totalChars + string.len(v)

This is the solution I’m using for this:

function getLineFromCursorPosition()
	local t = {}-- table to store the indices
	local i = 0
	while true do
		i = string.find(TextBox.Text, "\n", i+1)-- find 'next' newline
		if i == nil then break end
		table.insert(t, i)
	end
	for i2,v2 in pairs(t) do
		if v2>TextBox.CursorPosition-1 then
			return i2
		end
	end
	return #t+1
end

I grabbed the part that finds the position of the new lines from the official Lua.org documentation
Programming in Lua : 20.1

Works well enough for now, though I don’t know how well this will handle emojis

@RoyStanford You can’t do that in normal lua, but Roblox’s new Luau allows you to do that.

Edit: It seems to be handling emojis fine

1 Like

Oh wow I didn’t know that! Thanks for letting me know

How would I do this so it works with text wrapped? Sorry to bump an old topic.