lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



I've done it in Hamster (the Lua-based build tool) using tables. So each entry can be a number, string, or table (recursively). Only the _last_ user (the one actually reading the table) needs to 'unwrap' it, for which purpose I use:

-----
-- tbl= Loc_TableFlatten( val [,force_copy_bool] )
--
-- Returns a table without subtables (flattens contents into the main table).
-- Also removes any 'nil' or 'false' items.
--
-- Params: 'force_copy' may be used for ensuring the returned table is always -- a local copy of the provided one (even if they were identical). -- This is useful if the caller wants to later modify the contents.
--
-- Note: Tables are expected to be just containers (index values don't matter) -- but order is maintained (important for 'append' and 'prepend' functions).
--
local function Loc_TableFlatten( val, force_copy )
    --
    if not val then return nil; end

    if type(val) ~= "table" then  -- make scalars into a table
        return {val}
    end

    -- If already flat, skip making another table (optimization)
    --
    if not force_copy then
        if Loc_IsFlatTableWithoutNils(val) and (not val.n) then
            return val
        end
    end

    -- Find out largest index (note: there may be holes in the table!)
    --
    local ret= {}

    for i=1,getn(val) do    -- jump over holes
        --
        local v= val[i]

        if not v then     -- skip 'nil's and 'false's
            --
        elseif type(v)=="table" then
for _,v2 in ipairs( Loc_TableFlatten(v,force_copy) ) do -- keep order!
                table.insert( ret, v2 )
            end
        else
            table.insert( ret, v )
        end
    end

    return ret
end

ASSUME( _table.getn( Loc_TableFlatten( { 1,2,{3,4;n=2},5} ) ) == 5 )
ASSUME( _table.getn( Loc_TableFlatten( { 'a','b',[4]='c' } ) ) == 3 )



18.8.2004 kello 15:01, David Given kirjoitti:

Are there any workarounds I can use to fix this? I can have fn() return a table, in which case the table gets added to the list, but it's still added as a single item where I actually want the contents of the item instead...