Concatenation of tables in Lua

后端 未结 9 811
难免孤独
难免孤独 2020-12-09 15:04

ORIGINAL POST

Given that there is no built in function in Lua, I am in search of a function that allows me to append tables together. I have google

9条回答
  •  盖世英雄少女心
    2020-12-09 15:23

    In general the notion of concatenating arbitrary tables does not make sense in Lua because a single key can only have one value.

    There are special cases in which concatenation does make sense. One such is for tables containing simple arrays, which might be the natural result of a function intended to return a list of results.

    In that case, you can write:

    -- return a new array containing the concatenation of all of its 
    -- parameters. Scaler parameters are included in place, and array 
    -- parameters have their values shallow-copied to the final array.
    -- Note that userdata and function values are treated as scalar.
    function array_concat(...) 
        local t = {}
        for n = 1,select("#",...) do
            local arg = select(n,...)
            if type(arg)=="table" then
                for _,v in ipairs(arg) do
                    t[#t+1] = v
                end
            else
                t[#t+1] = arg
            end
        end
        return t
    end
    

    This is a shallow copy, and makes no attempt to find out if a userdata or function value is a container or object of some kind that might need different treatment.

    An alternative implementation might modify the first argument rather than creating a new table. This would save the cost of copying, and make array_concat different from the .. operator on strings.

    Edit: As observed in a comment by Joseph Kingry, I failed to properly extract the actual value of each argument from .... I also failed to return the merged table from the function at all. That's what I get for coding in the answer box and not testing the code at all.

提交回复
热议问题