[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Using getfenv or setfenv to create variables (Lua 5.1)
- From: Dirk Laurie <dirk.laurie@...>
- Date: Wed, 22 Nov 2017 12:47:53 +0200
2017-11-22 12:20 GMT+02:00 Xazo -Tak <xazotak@gmail.com>:
>
> Totally wiping out the fenv seems like a bad idea.
So does writing new software in Lua 5.1 when support for it stopped on
17 Feb 2012.
In Lua 5.3 you do all this with _ENV, which is cleaner.
> Plus, it's basically what I tried, except you have a "1" for some reason where I had module.main
That's a rather important difference. 1 means "the function calling
getfenv/setfenv". If this function is in turn called from the main
module, it has the environment of the main module as default, but the
whole purpose of setfenv is to give it its own environment so that
what looks like global variables in fact don't pollute the real global
table.
If you needed the old env and the new env at the same time, you could put
local oldenv = getfenv(1)
before doing setfenv.
If you really wanted to define new global variables, you could do this:
> function f(arg)
local _G = getfenv(0)
for k,v in pairs(arg) do _G[k]=v end
end
> f{x=24,y=25,z=26}
> print(x,y,z)
24 25 26
>
> On 22 November 2017 at 22:10, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>>
>> function f(arg)
>> local print=print -- before it becomes invisible
>> setfenv(1,arg)
>> print(x,y,z)
>> end
>>
>> > f{x=24,y=25,z=26}
>> 24 25 26
>>
>> 2017-11-22 7:59 GMT+02:00 Xazo -Tak <xazotak@gmail.com>:
>>>
>>> A function in my program takes an associative array as an argument then unpacks the array, converting key-value pairs into variables named after the keys they have the values of.
>>>
>>> Except that I cannot figure out how to unpack an associative array like that.
>>> I hear that it can be done with fenv functions, but I can't figure out how.
>>> I tried putting this into the function module.main, but it failed to assign a value to an already-existent nil variable:
>>>
>>> local fenv = getfenv(module.main)
>>>
>>> for key, value in pairs(arguments) do
>>>
>>> fenv[key] = value
>>>
>>> end
>>>
>>> setfenv(module.main, fenv)
>>
>>
>