lua-users home
lua-l archive

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


> Unfortunately though, I need to create access to all libraries again in 
that
> global space don't I?  or at least the libraries I want the user to be 
able
> to access.

Yep, but I think that is a strength.

> What's the overhead for that kind of "setting up" of a variable list? 
(if
> the objects already exist elsewhere in the system I presume its not that
> costly)

Depends how you do it. My fave is memoising lazy copy, but it may be 
overkill.

U:\>lua
Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> function inject(name)
>>   return function(environment)
>>     local pkg = getfenv()[name]
>>     local function getter(t, k)
>>       t[k] = pkg[k]
>>       return pkg[k]
>>     end
>>     environment[name] = setmetatable({}, {__index = getter})
>>     return environment
>>   end
>> end
>
> function make_env(...)
>>   local newenv = {next = next, pairs = pairs, ipairs = ipairs,
>>                   _TRACEBACK = _TRACEBACK, tostring = tostring,
>>                   print = print, -- etc
>>                  }
>>   newenv._G = newenv
>>   return newenv
>> end
>
> inject_math = inject "math"
> inject_table = inject "table"
> -- etc.
>
> sandbox = make_env()
>
> inject_math(sandbox)
> inject_table(sandbox)
> -- or
> inject "string"(sandbox)
>
> table.foreach(sandbox.math, print)
> =sandbox.math.atan(sandbox.math.sqrt(2))
0.95531661812451
> table.foreach(sandbox.math, print)
sqrt    function: 00441340
atan    function: 00443160
>