-- 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()