lua-users home
lua-l archive

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


Thanks,
         thats fine, yes for now I am just putting the required upvalues in the environment table with a metaindex to the current environment.

Milind



On Thu, Apr 17, 2014 at 2:24 PM, Andrew Starks <andrew.starks@trms.com> wrote:
On Thu, Apr 17, 2014 at 4:02 PM, Milind Gupta <milind.gupta@gmail.com> wrote:
> Thanks for your replies. Yes I would be really interested to see the code
> that finds out the locals and prepend them. Thanks!
>
> Regards,
> Milind
>
>
>
>
> On Thu, Apr 17, 2014 at 11:47 AM, Andrew Starks <andrew.starks@trms.com>
> wrote:
>>
>> On Thu, Apr 17, 2014 at 6:51 AM, Milind Gupta <milind.gupta@gmail.com>
>> wrote:
>> > Hi,
>> >           I have a trusted script that I want to load and execute and I
>> > want
>> > it to run in the current environment. How should I set the script
>> > environment and also pass all the current upvalues to the script?
>> >
>> > Thanks,
>> > Milind
>> >
>>
>> `load` allows you to specify _ENV, but neither load nor require[1]
>> will read in up values.
>>
>> One solution is to use the the package.searchpath [2] to find the
>> file. Read it in as a string and then prepend the locals to the top of
>> the file. Then `load` that.
>>
>> Hackery at its finest, but this is what I do and it works. If you'd
>> like, I can post that code. I won't, in case it would be too
>> offensive. :)
>>
>> -Andrew
>>
>> [1] My guess is that `require` does not allow _ENV to be set is
>> because it uses `package.loaded` to cache subsequent requests for the
>> same library. My guess is that it was decided that allowing the first
>> call to require for a specific module to define the environment for
>> all that use it was judged as "bad design."
>>
>> [2] http://www.lua.org/manual/5.2/manual.html#pdf-package.searchpath
>>
>

I should clarify. I'm not getting arbitrary upvalues and including
them in my _ENV. Instead, I'm prepending them to the loaded Lua code.

So, in short, the untested version of what I'm getting at is something like:

```
local pretty = require'pl.pretty' --pretty printer, for illustration purposes.

local my_table = {foo = "bar, baz = true, num = 1}

local my_file = io.open(file_name_from_package_searchpath)
local module = my_file:read("*a")

local prepend_stuff = [[
  local x = ]] .. tostring(x) .. [[
  local y = ]] .. tostring(y) .. [[
  local my_table = ]] .. pretty.write(my_table) .. ";\n"

return load(prepend_stuff .. module)
```
Extremely hack laden. I suspect that this is not what you were going for.

Given your expectation that I'm capturing all locals and including
them, I didn't go through the work of extracting the actual code from
my library (it's a bit too specific for general consumption). If this
doesn't help and you're still interested, let me know.

--Andrew