Lua 可以自动消除表达式和语句歧义的 REPS?

Lua REPL that can auto disambiguate expresssions and statements?

众所周知,Lua 5.3 以这种方式处理交互式 REPL 以区分表达式和语句:

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.

然而,这不是我想要的行为。例如,我有一些代码“f()”到 evaluate,其中 f 将通过错误,无论发生什么。它还会更改 lua 的内部状态。上面的做法会导致bug,因为它会两次改变内部状态。

所以,我想知道,有没有一种方法可以实现自动消除表达式和语句歧义的 REPL?我是否必须添加一些语法分析才能实现此目的?

解释 Lua REPL 中的代码是一个两步过程。首先,您使用 loadstring 或类似函数将输入转换为 运行nable 代码。该代码已被验证为正确,但尚未 运行。然后你明确地调用它。

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

总而言之,只要不调用结果,使用 loadstring() 或类似函数解析和验证代码是没有副作用的。