1

currently I am trying to export and re-import some variables in LUA. Imagine a table AllGlobals. The table contains all global variables used in my script, while key contains the variable name and value - surprise - contains the variable value.

What my script should do now is a reassignment of the variables. I started thinking about the following solution, which obviously isn't working:

1 function InsertGlobals()
2     for key,value in pairs(AllGlobals) do
3         key = value
4     end 
5 end

Well: Does anybody know a solution for assigning the value in line 3 to the variable name contained in key, not inserting it into the variable key itself?

2 Answers 2

1

Solution to my own problem:

function InsertGlobals()
    for key,value in pairs(AllGlobals) do
        _G[key]=value
    end
end 
Sign up to request clarification or add additional context in comments.

Comments

0

You are only doing a shallow iteration - you don't transverse over tables in tables. For example, the table input wouldn't put something like examp.newfunc() into the _G as _G.examp.newfunc(). Also, it isn't wise to duplicate references of _G, package, and _ENV unless you really know what you are doing, meaning having a purpose.

function InsertGlobals(input)
    for key, value in pairs(input) do
        if(key ~= "_G" or key ~= "package" or key ~= "_ENV")then
            _G[key] = value
        end
    end
end

To fix the shallow iteration, all you need to do is a little recursion. I am sure you won't blow your stack with this, but if you leave _G, package, and _ENV then you definitely will.

function InsertGlobals(input)
    for key, value in pairs(input) do
        if(key ~= "_G" or key ~= "package" or key ~= "_ENV")then
            if(type(value) ~= "table")then
                _G[key] = value
            else
                InsertGlobals(value)
            end
        end
    end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.