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

[recipe] Getting User Input

Started by Xab, 23 October 2014 - 07:24 PM
Xab #1
Posted 23 October 2014 - 09:24 PM
Here's a pretty neat recipe for when you want to get the user's input for something.
If the user enters the wrong kind of input in the promptt function, it will erase their entered text and lets the user try again, without starting a new line. It also provides a default value for a user: pressing enter will use the default value, or typing anything else will let the user enter their own value. Finally, I've included a function - promptYesNo - for answering simple yes/no questions in a similar way as promptt.

Spoiler


-- Prompts user for a non-nil value of a specified type, providing a specified default value
-- Returns a string, number, or boolean value
function promptt(msg, expType, default)
  msg = msg or ""
  expType = expType or "string"
  write(tostring(msg))
  local px, py = term.getCursorPos()

  while true do
	-- get user input
	local value
	if default then
	  write(default)
	  local _,key = os.pullEvent("key")
	  if key == keys.enter then
		value = default
		print()
	  else
		-- clear default value
		term.setCursorPos(px, py)
		write(string.rep(" ", string.len(default)))
		term.setCursorPos(px, py)
		value = read()
	  end
	else
	  value = read()
	end

	-- format value to correct type
	local strLen = string.len(value)
	if expType == "number" then
	  value = tonumber(value)
	elseif expType == "boolean" then
	  if string.upper(value) == "TRUE" then
		value = true
	  elseif string.upper(value) == "FALSE" then
		value = false
	  else
		value = nil
	  end
	end

	if value == nil or value == "" then -- if not a valid type..
	  -- clear user input
	  term.setCursorPos(px, py)
	  write(string.rep(" ", strLen))
	  term.setCursorPos(px, py)
	else
	  return value
	end
  end
end


-- Prompts user for a yes/no value
-- Returns true if "yes", false if "no"
function promptYesNo(msg)
  msg = msg or ""
  msg = msg.."(y/n): "
  write(msg)
  local px, py = term.getCursorPos()
  while true do
	local value = string.upper(read())
	if value == "Y" or value == "YES" then
	  return true
	elseif value == "N" or value == "NO" then
	  return false
	else
	  -- clear input
	  term.setCursorPos(px, py)
	  write(string.rep(" ", string.len(value)))
	  term.setCursorPos(px, py)
	end
  end
end


function main()
  local a = promptt("Enter a string: ")
  local b = promptt("Enter another string: ", "string", "ComputerCraft")
  local c = promptt("Enter a number: ", "number", "123456789")
  local d = promptt("Enter a boolean value: ", "boolean", "true")
  local e = promptYesNo("Having fun yet?")
  print(a)
  print(B)/>
  print(c)
  print(d)
  print(e)
end
main()


pastebin: pastebin get u5K7DCXi
theoriginalbit #2
Posted 24 October 2014 - 05:02 AM
Moved to APIs and Utilities.