This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Sewbacca's profile picture

Limit read()

Started by Sewbacca, 26 March 2016 - 11:36 AM
Sewbacca #1
Posted 26 March 2016 - 12:36 PM
How can I limit the read line?
I want to create a text box.
Bomb Bloke #2
Posted 26 March 2016 - 01:17 PM
Create a window, redirect term to that, then call read.
Sewbacca #3
Posted 26 March 2016 - 04:52 PM
It works thanks.
DannySMc #4
Posted 26 March 2016 - 10:11 PM
You could use something that I found a little while ago on the forums from someone I can't remember his name and this works how you like but just on the one line and limits the text, code:

function limitRead(limX, rChar)
	term.setCursorBlink(true)
	local origX, origY = term.getCursorPos()
	local returnString = ""
	while true do
		local xPos, yPos = term.getCursorPos()
		local event, p1, p2 = os.pullEvent()
		if event == "char" then
			returnString = returnString..p1
			if not rChar then
				if not limX then
					write(p1)
				else
					if string.len(returnString) >= limX then
						term.setCursorPos(origX, origY)
						write(string.sub(returnString, (string.len(returnString)-limX)+1))
					elseif string.len(returnString) < limX then
						write(p1)
					end
				end
			else
				if not limX then
					write(rChar)
				else
					if string.len(returnString) >= limX then
						term.setCursorPos(origX, origY)
						write(string.rep(rChar, limX))
					elseif string.len(returnString) < limX then
						write(rChar)
					end
				end
			end
		elseif event == "key" and p1 == 14 then --backspace
			returnString = string.sub(returnString, 1, (string.len(returnString))-1)
			term.setCursorPos(xPos-1,yPos)
			write(" ")
			term.setCursorPos(origX, origY)
			if string.len(returnString) >= limX then
				if not rChar then
					write(string.sub(returnString, (string.len(returnString)-limX)+1))
				else
					write(string.rep(rChar,limX))
				end
			else
				if not rChar then
					write(returnString)
				else
					write(string.rep(rChar, string.len(returnString)))
				end
			end
		elseif event == "key" and p1 == 28 then --enter
			break
		end
	end
	term.setCursorBlink(false)
	return returnString
end
Edited on 26 March 2016 - 09:12 PM
KingofGamesYami #5
Posted 26 March 2016 - 10:21 PM
I think that was Cranium's
DannySMc #6
Posted 27 March 2016 - 02:29 AM
I think that was Cranium's

Ahh yes it was! Sorry could never remember the name, I just know it was the most useful and lost code I needed xD