lua-users home
lua-l archive

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


Hi!

Some functions are better to be generated and "load"-ed on-the-fly
instead of be fully prepared in the source code.

At the moment, we are forced to use globals or pass separate environment
table to share variables with "load"-ed functions, which is not very handy.
It also implies frequent hash-table lookups, which is not very fast.

To make sharing local variables with "load"-ed functions nice and easy,
a new keyword, a new syntax and a new function can be introduced:

1) New keyword "upvalue" is used to mark some variables as upvalues
in current chunk and to assign consecutive negative upvalue indices to them

2) New syntax "@varname" is used to get "id" for locals and upvalues,
such "id" has the same meaning as values returned by "debug.upvalueid(f,n)"

3) New function "debug.useupvalue(f, n, id)" is a more powerful version
of old function "debug.upvaluejoin":
"debug.upvaluejoin(f1, n1, f2, n2)" is the same as
"debug.useupvalue(f1, n1, debug.upvalueid(f2, n2))"
But we also can write "debug.useupvalue(f, n, @variable_name)"
to use local variable "variable_name" from our current chunk
as an upvalue inside function "f".


Example:

local str = 'original'
do
  local x = 123
  local func = load("upvalue y,z; y = y + 1; print(y); z = 'modified'")
  -- "y" and "z" are upvalues, they are not auto-prefixed by "_ENV."
  -- Negative indices starting with -1 are assigned to "y" and "z"
  -- Function "func" has three upvalues: _ENV, y and z,
  -- which have indices 1, (-1) and (-2) accordingly.
  -- Index (-1) is the same as 3, index (-2) is the same as 2.
  debug.useupvalue(func, -1, @x)
  -- "@x" is an _expression_, which returns the "id" for variable "x"
  -- our local variable "x" is now used as upvalue with index -1 in "func"
  debug.useupvalue(func, -2, @str)
  -- "@str" is an _expression_, which returns the "id" for upvalue "str"
  -- our upvalue "str" is now used as upvalue with index -2 in "func"
  func()      -->  124
  print(x)    -->  124
  print(str)  -->  modified
end


-- Egor