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

How do I read an input while it is being read?

Started by greygraphics, 15 May 2016 - 02:21 PM
greygraphics #1
Posted 15 May 2016 - 04:21 PM
Hey,

you know how the shell in CC automatically suggests the file endings when typing the first letter?
I am curious how this is done. Is it via os.pullEvent("key") or via io.read()? And how do you read the io.read() value while it is being typed?
I already had a look at the code for the shell, but I could not figure out how they do this.
So, how is this magic performed?
Dragon53535 #2
Posted 15 May 2016 - 11:07 PM
More or less it's the read function, however with a certain argument as a function for generating a table of autocompletions

Read Function Source

_sReplaceChar is a string for replacing characters that they type with something else, so

read("*")
Will make all characters they type appear as *

_tHistory is a table containing previously submitted things, so that if you press the up arrow or down arrow as you do in the lua program it pops up what you had before.

and _fnComplete is a function pointer, this function should return a table that is then used for autocompletion.
greygraphics #3
Posted 16 May 2016 - 12:25 PM
So, when I want to let's say make a redstone switch with on/off commands, I would have to

local input = read("",{},{"on","off"})
?
KingofGamesYami #4
Posted 16 May 2016 - 02:13 PM
So, when I want to let's say make a redstone switch with on/off commands, I would have to

local input = read("",{},{"on","off"})
?

Nope. I could still enter "hello world!" or whatever I want. There isn't any way to limit read().
Bomb Bloke #5
Posted 16 May 2016 - 03:53 PM
That third parameter would need to be a function, not a table. IIRC, functions along the lines of the ones you'd pass to shell.setCompletionFunction() would work.

But that's not really the best way to go about it - as Yami points out, the autocompletion system doesn't stop users from typing whatever they want. It also doesn't suggest anything until the user starts typing, and if both of your choices start with the same letter, then it becomes even less useful!

If you want to give the user a set list of choices, I suggest listing them out and waiting for them to pick one, eg via typing a number:

print("What do you want to do?")
print("1) Turn thing on")
print("2) Turn thing off")

while true do
	local event, key = os.pullEvent("key")
	
	if key == keys.one then
		turnThingOn()
		break
	
	elseif key == keys.two then
		turnThingOff()
		break
	end
end
Dragon53535 #6
Posted 16 May 2016 - 11:01 PM
You could try.

read(nil,nil,function() return {"On","Off"} end)
greygraphics #7
Posted 17 May 2016 - 08:28 PM
Hey, thanks for all your answers, the redstone was just a small example, but I think I got the read function kind of figured out now.