diff --git a/Libraries/LibJS/Interpreter.cpp b/Libraries/LibJS/Interpreter.cpp index b038cd8c6c..0a49fb5cea 100644 --- a/Libraries/LibJS/Interpreter.cpp +++ b/Libraries/LibJS/Interpreter.cpp @@ -70,7 +70,9 @@ Value Interpreter::run(const Statement& statement, ArgumentVector arguments, Sco auto& block = static_cast(statement); enter_scope(block, move(arguments), scope_type); - m_last_value = js_undefined(); + if (block.children().is_empty()) + m_last_value = js_undefined(); + for (auto& node : block.children()) { m_last_value = node.execute(*this); if (should_unwind()) { @@ -176,7 +178,10 @@ Value Interpreter::get_variable(const FlyString& name) return possible_match.value().value; } } - return global_object().get(name); + auto value = global_object().get(name); + if (m_underscore_is_last_value && name == "_" && value.is_empty()) + return m_last_value; + return value; } Reference Interpreter::get_reference(const FlyString& name) diff --git a/Libraries/LibJS/Interpreter.h b/Libraries/LibJS/Interpreter.h index 0e877f5049..9219ea6d39 100644 --- a/Libraries/LibJS/Interpreter.h +++ b/Libraries/LibJS/Interpreter.h @@ -177,6 +177,9 @@ public: Value last_value() const { return m_last_value; } + bool underscore_is_last_value() const { return m_underscore_is_last_value; } + void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; } + Console& console() { return m_console; } const Console& console() const { return m_console; } @@ -199,6 +202,8 @@ private: ScopeType m_unwind_until { ScopeType::None }; FlyString m_unwind_until_label; + bool m_underscore_is_last_value { false }; + Console m_console; }; diff --git a/Userland/js.cpp b/Userland/js.cpp index 990e5133bf..39258dc2ae 100644 --- a/Userland/js.cpp +++ b/Userland/js.cpp @@ -575,6 +575,7 @@ int main(int argc, char** argv) ReplConsoleClient console_client(interpreter->console()); interpreter->console().set_client(console_client); interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation); + interpreter->set_underscore_is_last_value(true); if (test_mode) enable_test_mode(*interpreter);