Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "Prompt" function for user input #452

Open
MHippo opened this issue Jan 23, 2024 · 1 comment
Open

Add "Prompt" function for user input #452

MHippo opened this issue Jan 23, 2024 · 1 comment

Comments

@MHippo
Copy link

MHippo commented Jan 23, 2024

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!"
@wackbyte
Copy link
Contributor

wackbyte commented Jan 23, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants