lua-users home
lua-l archive

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




On Monday, June 8, 2015, Soni L. <fakedme@gmail.com> wrote:


On 08/06/15 06:40 PM, Coda Highland wrote:
On Mon, Jun 8, 2015 at 2:09 PM, Soni L. <fakedme@gmail.com> wrote:

On 08/06/15 06:05 PM, Soni L. wrote:

I wish you could access your own locals with an _LOCAL[idx] that would be
faster than debug.getlocal...

Not sure how that'd work if you local x = _LOCAL, or called a function with
_LOCAL...

Actually I do know, _LOCAL tables would be like any other tables, but
heavily optimized for this kind of stuff, and it'd be part of the function's
call stack entry thingy. The GC can take care of the rest.
function locals()
return setmetatable({ [0]={} }, {
     __index = function(t, k)
             local ki = t[0][k]
             assert(ki, "attempt to read nonexistent local")
             local ln, lv = debug.getlocal(2, ki)
             assert(ln == k, "inconsistent state")
             return ln
         end,
     __newindex = function(t, k, v)
             local ki = t[0][k]
             if not ki then
                 local i = 0
                 while true do
                     i = i + 1
                     local ln, lv = debug.getlocal(2, i)
                     if ln == k then
                         ki = i
                         break
                     elif not ln then
                         break
                     end
                 end
                 assert(ki, "attempt to assign nonexistent local")
             end
             debug.setlocal(2, ki, v)
         end
})
end

_LOCAL = locals()

Untested... but that's about as good as you're going to get.

/s/ Adam

Not faster than debug.getlocal, cannot be passed around, cannot be indexed with NUMBERS, doesn't give access to varargs... What else? (I guess the varargs part would be really awesome tbh, just changing varargs on the fly, accessing them at 0 (or at least little) cost, etc... Can debug.setlocal() be used to set varargs?)

--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.



Perhaps instead, you could ask for a more general "state" table. This is achievable, right now, more or less? It would rely on __index, of course.