How do I unpack tables into another table, without inserting empty ones?

I have three types of crates in my levels that I spawn on load.

local push_crates = { search_and_spawn( "crates", level_data.PUSH_CRATE, "/level_spawner#factory_crate_push", false ) }
local slide_crates = { search_and_spawn( "crates", level_data.SLIDE_CRATE, "/level_spawner#factory_crate_slide", false ) }
local pull_crates = { search_and_spawn( "crates", level_data.PULL_CRATE, "/level_spawner#factory_crate_pull", false ) }

I then wanted to put them linearly into another table:

level_data.crates = { unpack(push_crates), unpack(slide_crates), unpack(pull_crates) }

However, the rest of the code breaks if one or more of the types are missing form the level. It didn’t start working until I did this whole mess:

	if #push_crates > 0 and #slide_crates > 0 and #pull_crates > 0 then
		level_data.crates = {
			unpack(push_crates),
			unpack(slide_crates),
			unpack(pull_crates)
		}
	elseif #push_crates > 0 and #slide_crates > 0 then
		level_data.crates = {
			unpack(push_crates),
			unpack(slide_crates)
		}
	elseif #slide_crates > 0 and #pull_crates > 0 then
		level_data.crates = {
			unpack(slide_crates),
			unpack(pull_crates)
		}
	elseif #push_crates > 0 and #pull_crates > 0 then
		level_data.crates = {
			unpack(push_crates),
			unpack(pull_crates)
		}
	elseif #push_crates > 0 then
		level_data.crates = {
			unpack(push_crates)
		}
	elseif #slide_crates > 0 then
		level_data.crates = {
			unpack(slide_crates)
		}
	elseif #pull_crates > 0 then
		level_data.crates = {
			unpack(pull_crates)
		}
	end

I’m guessing it happens when any of the tables are empty, it still inserts, something, nil or an empty table.
Any idea how to shorten that code? :smile:

What about this:

level_data.crates = {}
if #push_crates > 0 then
   table.insert(level_data.crates, push_crates)
end
if #slide_crates > 0 then
   table.insert(level_data.crates, slide_crates)
end
if #pull_crates > 0 then
   table.insert(level_data.crates, pull_crates)
end

EDIT: Nope, I misread what you wanted to achieve… sorry. New try:

level_data.crates = {}

local function append_crates(crates_to_append)
   for _,crate in ipairs(crates_to_append) do
       table.insert(level_data.crates, crate)
   end
end

append_crates(unpack(push_crates))
append_crates(unpack(slide_crates))
append_crates(unpack(pull_crates))
1 Like

Ah, of course, thanks!