How to pass a variable by reference or workaround that issue (Want to create a variable watch)

My idea is to create a variable watch like you have when using the watch() function. But I want to see this variables as overlay over my fullscreen App which I could set on and off at runtime. To achieve this I wrote a debug function which I could pass one or more variables and the content of that variable is shown on the screen. See the code below.

It works, when the variable is a table or of some other type which is passed by reference. But I found in the documentation, that standard variables like numbers are only passed by value. I did not find a way to pass it by reference. I have worked around that by using a table for a normal number… which is not what I wanted to do.

So my question is, if there is any possibility to solve this more elegant than using a table with one entry for a variable. Maybe I can put a watch variable into a table dynamically and then pass that?

Now to the code (It currently extracts only the first value of the table, normally I would have to iterate, but this is just a draft):

--Variable I want to watch:
vartest = {0}

--Init function:
debug.watch(vartest)

-- Draw function:
debug.draw()
vartest[1] = vartest[1] + 1 -- To see changes

Now to the debug code:
--------------------

local varTable = {}

local watch = function(variable)
    table.insert(varTable, variable)
end

local draw = function()
    pushStyle()
        font("Inconsolata")
        fontSize(16)
        textMode(CORNER)
        textAlign(LEFT)
        textWrapWidth(0)
        local h = 300
        fill(0, 0, 0, 128)
        noStroke()
        rect(0, HEIGHT - h, WIDTH, h)
        local y = HEIGHT - 16
        for i = 0, table.maxn(varTable) do
            if varTable[i] ~= nil and y > HEIGHT - h then
                local l = varTable[i]
                local s = string.format("%s", l[1])
                fill(0, 0, 0, 255)
                text(s, 1, y - 1)
                fill(255, 255, 255, 255)
                text(s, 0, y)
                y = y - 16
            end
        end
    popStyle()
end


debug = {
    watch = watch,
    draw = draw
}

Hello! I had two thoughts. First, by choosing the namespace debug you overwrite the Lua standard library of that name. Second, had you considered making use of the environment? If you watch the name of a global variable as a string (s = "myVariable") you can access its value as _G[s].

Thanks @mpilgrem. _G works, now I have to print the data on the screen depending on the variable type, I will figure that out. I did not know, that there is a debug namespace already present… I will rename mine.

My plan is finally to split the screen into logs (your print redirect) and the variable watch.