Search code examples
lua

My program filters some uneven numbers but also some even numbers


So I need to write a program which gets a table as an input and gives the same table as an output without the values with even keys. So basically I need to filter out the even keys and their values and leave the uneven keys with their values.

local function selecteer_oneven(tabel)
    for q, n in ipairs(tabel) do
    if (q % 2) == 0 then
      table.remove(tabel, q)
    end
  end
  return tabel
end

local function printtabel(tabel)
    for k,v in pairs(tabel) do
        print(k,v)
    end
end

io.write("Geef een lua-tabel: ")
local tabelstring = "t = "..io.read()
local string2tab = loadstring(tabelstring)
string2tab()
local resultaat = selecteer_oneven(t)
printtabel(resultaat)

my input is

{ "aap", "kat", "hond", "paard", "kip", "salamander", "programmeren is leuk" }

and my output is

1   aap
2   hond
3   paard
4   salamander
5   programmeren is leuk

(sorry it is in Dutch)

"Aap", "Hond", "Programmeren is leuk" are the only uneven ones. "paard", and "salamander" are even.


Solution

  • Dont do table.remove on the table you are checking at same time.
    Better do a second local table and insert q.
    And finaly return the second table...

    local function selecteer_oneven(tabel)
        local tabel2={}
        for q, n in ipairs(tabel) do
        if (q % 2) ~= 0 then
          table.insert(tabel2, q)
        end
      end
      return tabel2
    end
    

    ...dont tested - yet ;-)

    EDIT: Tested with lua -i

    -- <ready>
    >function selecteer_oneven(tabel)
        local tabel2={}
        for q, n in ipairs(tabel) do
        if (q % 2) ~= 0 then
          table.insert(tabel2, q)
        end
      end
      return tabel2
    end
    -- <ready>
    >dump(selecteer_oneven({1,2,3,4,5,6,7,8,9,10}))
    1=1
    2=3
    3=5
    4=7
    5=9
    -- <ready>
    >-- whats dump?
    -- <ready>
    >code.dump
    -- dump()
    return function(dump)
    for key,value in pairs(dump) do
      io.write(string.format("%s=%s\n",key,value))
    end
    end
    -- <ready>