0

I'm creating an inline code editor as a teaching tool. I'd like to be able to execute a string of code, then execute another string of code, and have both run in the same namespace, so the second eval can access variables defined in the first. Ideally, this'll run in a sandbox namespace, not global. But I could work with global if needed. Since this is a teaching tool, I want to be able to specify the variables in the string in the standard format. So the first eval string might be "var x=5;" and the second could be "console.log(x)", and should log 5.

Here is a jsfiddle code. If you could rewrite the function to get console to log "777" based on the existing data, that would be dandy.

VIzt6uNhBQ

Dave B
  • 21
  • 1
  • 5
  • Does this answer your question? [Context-preserving eval](https://stackoverflow.com/q/67322922/1048572) – Bergi Oct 09 '22 at 16:40
  • 1
    "*Here is a jsfiddle*" - there's no link, but even if there were, please [post your code not just a link to it](https://meta.stackoverflow.com/q/254428). Make it a [stack snippet](https://meta.stackoverflow.com/q/358992). – Bergi Oct 09 '22 at 21:26

1 Answers1

2

Here's a basic asynchronous Read Eval Print Loop I just wrote:

var inputElement = document.createElement('input')
document.body.appendChild(inputElement)

function __read() {
  return new Promise((resolve) => {
    let listener = (e) => {
      if (e.key === 'Enter') {
        inputElement.removeEventListener('keydown', listener)
        let v = inputElement.value
        inputElement.value = ''
        resolve(v)
      }
    }
    inputElement.addEventListener('keydown', listener)
  })
}

async function repl() {
  while (true) {
    console.log(eval(await __read()))
  }
}

repl()

The variables are all kept inside the repl() function.

Mathieu CAROFF
  • 1,230
  • 13
  • 19