Search code examples
luaread-eval-print-loop

Lua REPL that can auto disambiguate expresssions and statements?


As it is known, Lua 5.3 handles interactive REPL to differentiate expressions and statements this way:

In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

However, this is not the behavior I want. For example, I have some codes "f()" to evaluate, where f will through error, no matter what happens. it also change the internal state of lua. The above approach will cause bugs because it will change the internal state twice.

So, I'd like to know, is there a way to implement a REPL that auto disambiguate expressions and statements? Do I have to add some syntax analysis to achieve this?


Solution

  • Interpreting code in Lua REPL is a two step process. First you convert the input to a runnable code with loadstring or a similar function. The code has been validated to be correct but didn’t run yet. Then you explicitly invoke it.

    fn = loadstring(“return 42”); fn()

    To summarize, parsing and validating code with loadstring() or a similar function is side effect free, as long as you don’t invoke the result.