lua-users home
lua-l archive

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


On Wed, Apr 9, 2014 at 10:33 AM, steve donovan
<steve.j.donovan@gmail.com> wrote:
> But this cure is arguably uglier than the disease...

Ah, but it doesn't look so bad if you let it run onto one line:

local insert, concat = slots(2) from (table)
local sin, cos = slots(2) from (math)

And here is an implementation sketch; a more optimized one would keep
track of the last slot used for a particular function, and call
require() if passed a string.  Not terribly fast, but probably ok for
once-off initializations in a module.

It works, but ... just for entertainment value, you know ;)  (Easy to
port to 5.2)

-----------------
local nslots

function slots (n)
    nslots = n
    local res = {}
    for i = 1,n do res[i] = true end
    return unpack(res)
end

function from (T)
    local slot = 1
    -- collect all the active locals
    local locals, append = {}, table.insert
    while true do
        local loc,v = debug.getlocal(2,slot)
        if not loc then break end
        append(locals,loc)
        slot = slot + 1
    end
   -- and set the last ones
    for i = #locals-nslots+1,#locals do
        debug.setlocal(2,i,T[locals[i]])
    end
end
--------------