lua-users home
lua-l archive

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


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)