Search code examples
lualua-table

LUA, table.insert and nested tables, with the condition to only insert tables if not already there


So this is basically what i'm dealing with

datavalues={{VALUE=896},{VALUE=965},{VALUE=569}}

I do need nested table, because i'm going to modify each nested table with an added timestamp later on, when some checks are met after some iteration, with the following line

datavalues[i].TIMESTAMP=something

the nested tables are then going to look something like this

datavalues={{VALUES=896, TIMESTAMP=596664},{VALUES=965, TIMESTAMP=597864},{VALUES=569, TIMESTAMP=597864}}

This has been manually populated ofc, but i do not want that! i want to only populate through some function.

The naive solution that I tried, (and of course it doesn't work)

datavalues={}
function addtotable(id)
    if #datavalues==0
        then table.insert(datavalues,{VALUE=id})
    end
    if #datavalues>0
        then for i=1,#datavalues do
            if datavalues[i].VALUE==id
                then break
                else table.insert(datavalues,{VALUE=id})
            end
        end
    end
end

The wanted behavior is: when I use this function twice for the same value (say addtotable(595)), it only works the first time (only adds unique values once)

the current behavior : it doesn't work, it works for one value, if I add a second value and retry re-adding the first, it just adds the same value in another nested table when it shouldn't

It is important for me to keep the scruture of the table i posted earlier also!

EDIT: So basically what happens: addtotable(168) is ran once or x amount of time :

datavalues={{VALUE=168}}

this is expected

addtotable(168) is run once then addtotable(169) is run many times

datavalues={{VALUE=168},{VALUE=169},{VALUE=169},{VALUE=169},{VALUE=169},{VALUE=169},....} etc

i want to fix this behavior and only have

datavalues={{VALUE=168},{VALUE=169}} no matter how many times i run each

Solution

  • Error marked in code:

    datavalues = { }
    function addtotable(id)
        if #datavalues==0
            then table.insert(datavalues,{VALUE=id})
        end
        if #datavalues>0 then
            for i=1,#datavalues do
                if datavalues[i].VALUE==id then
                    break
                else
                    --right here is your error. Each time an entry does not match, you add another entry.
                    table.insert(datavalues,{VALUE=id})
                end
            end
        end
    end
    

    You may want something like this:

    datavalues = { }
    function addtotable(id)
        for i=1,#datavalues do
            if datavalues[i].VALUE==id then
                return --don't execute anything else
            end
        end
    
        --we can only end up here if return has never been called, thus no entry has been found
        table.insert(datavalues,{VALUE=id})
    end