Saturday, March 15, 2025

Closures in Lox

I made closures in Lox to capture local variables outside the functions.


closure() is a closure that captures a variable.

This is the disassembly of the main function:


a variable is closed with OP_CLOSE_VALUE instruction

We can see that it prints 3 two times since a is closed at the end of the for loop and since Lox captures variables and not values both closures globalOne and globalTwo print the same variable reference!



The  Lox Closure system is made in the runtime. I made it in the virtual machine. and the variables are closed in the heap since the stack is gone once the two calls are made.




No comments:

Post a Comment