Tables as function parameters for merging tables (help!!!)


This really shouldn’t be difficult, but I cannot get this to work…

I have a table in ‘map’ form which represents the style attributes of a UI panel, passed in when a panel is created. I have a global UIManagerStyle table which contains default values for anything not set on a per-panel basis…

I want to merge these tables in a function… But it just does not work. The # operator always returns zero, here is an example to clarify using global tables:

-- Scratch

-- Globals just to test
mergeTo = {a = 1, b = 2 }
mergeFrom = {b = 3, c = 4 }
-- Use this function to perform your initial setup
function merge1()
    print("#mergeTo :"..#mergeTo)            -- Prints zero
    print("#mergeFrom: "..#mergeFrom)    -- Prints zero
    for k, v in ipairs(mergeFrom) do
        print("mergeFrom.k: "..mergeFrom[k]) -- Never gets here
        if(mergeTo[k] ~= nil) then
            print("Merging value from key: "..k)
            mergeTo[k] = v
    return mergeTo -- Required?

-- Use this function to perform your initial setup
function setup()
    print("Hello World!")
    mergeTo = merge1()
    print("mergeTo.b: "..mergeTo.b)

-- This function gets called once every frame
function draw()
    -- This sets a dark background color 
    background(40, 40, 50)

    -- This sets the line thickness

    -- Do your drawing here


I *know* this must be related to pass by reference/value, implicit local variables or similar, but I just can't get it...

I just want a generic merge tables function...

Even passing the mergeTo table out of the function and reassigning it doesn't work...

Any help gratefully appreciated,


Replace ipairs by pairs.
ipairs is for index 1 to n, without inturruption (eg: 1,2,5,6) stops at 2.
Pairs is for any index.

And #myTable works with integer index only, without inturruption, starting at 1.

Many, many thanks, works a treat now,