moonscript
moonscript copied to clipboard
Add "Prompt" function for user input
a function that work's like Typescript's
Code examples
normal usage
name = prompt("What's your name?: ")
print "hello, {@name}!"
pre-set value
age = prompt("How old are you?", 18) -- when given nil, it will set the variable @age to 18
print "you are {@age} years old!"
Since it compiles directly to Lua, MoonScript doesn't have a standard library that could include this.
If you want a function similar to JavaScript's prompt, you could try this:
prompt = (text, default) ->
io.write text
input = io.read!
if input ~= nil and #input > 0
input
else
default
age = prompt "How old are you? ", 18
print "you are #{age} years old!"
-- note: the string interpolation syntax uses #{...}, and @name translates to self.name
Note that JavaScript's prompt will use the default value when the modal is closed without clicking OK. Since the terminal is just text in-and-out, this implementation uses the default value when the input line is empty or the end of the input is reached. (This is more similar to Python's input.)