Skip to content

Instantly share code, notes, and snippets.

@ryanpcmcquen
Last active November 14, 2021 22:33
Show Gist options
  • Save ryanpcmcquen/7aca8ba7f9bce67d3a375fee72094cf3 to your computer and use it in GitHub Desktop.
Save ryanpcmcquen/7aca8ba7f9bce67d3a375fee72094cf3 to your computer and use it in GitHub Desktop.
Kind of like `Object.assign()` for Lua.
local function combineTables(...)
local combinedTable = {}
local arg = {...}
for k, v in pairs(arg) do
if type(v) == 'table' then
for tk, tv in pairs(v) do
table.insert(combinedTable, tv)
end
end
end
return combinedTable
end
@ha6000
Copy link

ha6000 commented Oct 23, 2020

I think this works better

function table.assign(...)
    local newTable = {}
    local arg = {...}

    for k, v in pairs(arg) do
        if type(v) == 'table' then
            for tk, tv in pairs(v) do
                newTable[tk] = tv
            end
        end
    end

    return newTable
end

@ryanpcmcquen
Copy link
Author

More performant?

@ryanpcmcquen
Copy link
Author

@ha6000, that is functionally different than combineTables:
https://repl.it/@ryanpcmcquen/PeacefulGeneralKeyboard#main.lua

one = { 'ctrl', 'alt' }
two = { 'shift' }

print_it(combineTables(one, two))

--[[
1   ctrl
2   alt
3   shift
--]]

print_it(table.assign(one, two))

--[[
1   shift
2   alt
--]]

@ha6000
Copy link

ha6000 commented Oct 24, 2020

yes? but more close to Object.assign

@ryanpcmcquen
Copy link
Author

@ha6000, I should have clarified, I am thinking of JavaScript's Object.assign():

https://repl.it/@ryanpcmcquen/CoarseCorruptDiskdrive

Object.assign(
    { 1: 'ctrl', 2: 'alt' },
    { 3: 'shift' }
);

// { 1: 'crtl', 2: 'alt', 3: 'shift' }

@ha6000
Copy link

ha6000 commented Oct 26, 2020

but, I would say mine is more close to object.assign, I might be understanding you incorrectly by what you mean.

const one = ['ctrl', 'alt'];
const two = ['shift'];

console.log(Object.assign(one, two));
// [ 'shift', 'alt' ]

@ryanpcmcquen
Copy link
Author

Object.assign isn't meant to apply to arrays. What are you trying to accomplish with your snippet?

@ha6000
Copy link

ha6000 commented Oct 26, 2020

Yeah I agree with that, but my code would do the same as Object.assign would do, which is what the gist is trying to do (I think, but this is what came up when searching for that).

@ha6000
Copy link

ha6000 commented Oct 26, 2020

This gist is more like concat

@ryanpcmcquen
Copy link
Author

It wouldn't do the same things for objects though. The intention of the gist is to combine tables.

@ryanpcmcquen
Copy link
Author

This does for tables what Object.assign does for objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment