Home

Remove Empty Strings From The End Of A List In Lua

I needed to remove empty strings from the end of a table. This is what I ended up with:

lua
local function remove_trailing_empty_lines(source)
  local reversed = {}
  local load_counter = #source
  local hit_content = false
  while load_counter > 0 do
    if source[load_counter] ~= "" then
      hit_content = true
      table.insert(reversed, source[load_counter])
    elseif hit_content == true then
      table.insert(reversed, source[load_counter])
    end
    load_counter = load_counter -1
  end
  local trimmed = {}
  local reverse_counter = #reversed
  while reverse_counter > 0 do
    table.insert(trimmed, reversed[reverse_counter])
    reverse_counter = reverse_counter - 1
  end
  return trimmed 
end

local source = { "a", "b", "c", "" }
local updated = remove_trailing_empty_lines(source)

print(#updated)
print(updated[1])
print(updated[2])
print(updated[3])
results start
~ fin ~