darkfrei
darkfrei

Reputation: 586

How to remove from table start and end elements

I need a smart solution for such situation. I have a list of values such as: {'a', 'b', 'abc', 'd', 'e', 'abc'}

As you can see, the string 'abc' comes twice. I need to delete all elements before first 'abc' and all elements after last 'abc'.

local list = {'a', 'b', 'abc', 'd', 'e', 'abc'}
local doubled_value = get_doubled_value  (list) -- returns 'abc'
for i = 1, #list do
  if not (list[1] == doubled_value) then
    table.remove(list, 1)
  else
    break
  end
end

Upvotes: 1

Views: 141

Answers (1)

Darius
Darius

Reputation: 1180

table.remove is very slow, the easiest way is to create an index for values and make new list:

<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">

function doubled_list(list)
  local index = {}
  for i,n in ipairs(list) do
    if index[n] then
      local newlist = {}
      for j = index[n],i do
        newlist[#newlist + 1] = list[j]
      end
      return newlist
    end
    index[n] = i
  end
  return list
end

local list = doubled_list({'a', 'b', 'abc', 'd', 'e', 'abc', 'f', 'g'})

print(table.concat(list,','))

</script>

Upvotes: 2

Related Questions