lua-users home
lua-l archive

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


I just came across an undocumented feature of the Lua 5.1
string.dump.  In Lua 5.0, string.dumping a function with
upvalues causes an error.  In Lua 5.1 and 5.1.1, such a
function can be dumped, and it does have upvalues
(initialized to nil and not shared with any other
functions).  (Example code is below.)

This is a handy if small subset of upvalue functionality,
but I was wondering why it's undocumented:

- It doesn't work in all situations?
- It was too complicated to explain in the manual?
- It's likely to change in the future (perhaps because of VM
 changes)?
- It was overlooked when updating the manual?

Here's an example:

 function DumpTest()
   local Acc = 100

   -- Increments and prints its upvalue:
   local function Inc()
     Acc = (Acc or 0) + 1
     print(Acc)
   end -- Inc

   -- Decrements and prints its upvalue:
   local function Dec()
     Acc = (Acc or 0) - 1
     print(Acc)
   end -- Dec

   local IncBc, DecBc = string.dump(Inc), string.dump(Dec)
   local Inc2, Dec2 = loadstring(IncBc), loadstring(DecBc)
   Inc() --> 101
   Inc() --> 102
   Dec() --> 101
   Dec() --> 100
   Inc() --> 101
   Inc2() --> 1
   Inc2() --> 2
   Dec2() --> -1
   Dec2() --> -2
   Inc2() --> 3
 end -- DumpTest
 DumpTest()

Thanks,

--
Aaron