lualua-tablefivem

Trying to figure out how to Grab part of a table. (hard to explain fully)


So, what i am trying to do is... well it's best to show. Also, this is about FiveM and I'm trying to modify an existing resource.

BMProducts = {
{
["lostItems"] = {
[1] = { name = "weapon_shotgun", price = 1500, crypto = 2500, amount = 1 },
},
}
}

table.insert(BMProducts, {
["ballasItems"] = {
[1] = { name = "weapon_pistol", price = 1500, crypto = 2500, amount = 1 },
},
})

Config.Products = BMProducts

And I have a another config, that I need to pull the Correct table, but now sure entirely how

["products"] =  Config.Products["ballasItems"],

Is what I have but it won't read it, due to what I assume is what i saw when debugging, that when inserting to the table, it assigns a number, ie;

[1] = {lostitems = {...
[2] = {ballasItems = {...

One that works, but what my ultimate goal is to make the code plug and play with the table inserts, is this

BMProducts = 
{
["lostItems"] = {
[1] = { name = "weapon_pistol", price = 1500, crypto = 2500, amount = 1 },
},
["ballasItems"] = {
[1] = { name = "weapon_pistol", price = 1500, crypto = 2500, amount = 1 },
},
}

which works with the config above because the way just above does not assign numbers and not inserting into a table. Any ideas how i can go about setting that config for the correct Products table?

When i try it with the table insert, and with the

["products"] =  Config.Products["ballasItems"],

It can't find the table, which is due to what i assume the table format being different than what it was, which was the code block at the bottom

so my main thing, is to get

["products"] =  Config.Products["ballasItems"],

to = the correct table when there is a table insert.


Solution

  • If you don't want to table.insert, then don't table.insert:

    BMProducts["ballasItems"] = {
        { name = "weapon_pistol", price = 1500, crypto = 2500, amount = 1 },
    }
    

    Now I think you told to not modify the config, so another approach is to just use that additional array index when indexing:

    ["products"] = Config.Products[2]["ballasItems"]
    

    Which obviously assumes that the config never changes and the entry with ballasItems is on index 2.

    If you do not know the index, you may want to iterate over Config.Products and look for the right product.

    for i,v in ipairs(Config.Products) do
        if v["ballasItems"] then
    
        end
    end
    

    You may also consider the case where two or more products match.