lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Gangadhar NPK wrote:
In this scenario, the question I have is - when does the value x
change from being a variable on the stack to a value within the
upValue. How is this transition done transparent to the caller. If you
think this is too basic a question and I ought to figure this out,
please let me know the source file and I shall try to figure it out.

Lua has a close opcode. It gives a stack position, and any "open" upvalues, ie upvalues pointing to the stack, above (or equal to, I believe) that stack position are closed. Closing upvalues involves copying the current stack data to the space reserved for a tvalue within the UpVal struct, and setting the pointer to point to that tvalue. Thus future getupval/setupvals won't attempt to modify the stack.

Close is inserted automatically by the compiler when variables go out of scope. Ie, if you're creating closures inside a for loop it'll insert a close at the bottom to ensure that the closures created access the correct iterator variable, but variables declared above that block will not be closed (as all closures created inside the for loop should share access to those).

Also, whenever a function returns it closes all upvalues down to reg 0. So there won't be a OP_CLOSE on your example, it's implicit. This is only done if lua has any open upvalues, but one thing I've noticed is that performance can be further improved (quite noticeably in synthetic compiler shootout benchmarks) by only doing it if the function returning has sub-protos. (As there's nearly always an open upvalue somewhere, yet few functions actually create closures).

- Alex