#Need help with a small challenge on coding fundamentals

1 messages · Page 1 of 1 (latest)

obtuse prism
#

In this code I'm trying to make it so whenever a proximity prompt is triggered, depending on what item it is, the value will become true in a dictionary and added to an array. Then it will print the array once there is something there. However nothing is ever added to the array even when I use table.insert

local noodles = workspace.Noodles
local tofu = workspace.Tofu
local tomato = workspace.Tomato

local menu = {
    [noodles] = false,
    [tofu] = false,
    [tomato] = false,
}

local selectedIngredients = {}

local function noodlesSelected()
    menu[noodles] = true
    for menuChoice, value in pairs(menu) do
        if value then
            table.insert(selectedIngredients, menuChoice)
        end
    end
end

local function tofuSelected()
    menu[tofu] = true
    for menuChoice, value in pairs(menu) do
        if value then
            table.insert(selectedIngredients, menuChoice)
        end
    end
end

local function tomatoSelected()
    menu[tomato] = true
    for menuChoice, value in pairs(menu) do
        if value then
            table.insert(selectedIngredients, menuChoice)
        end
    end
end

if #selectedIngredients > 0 then
    print("You selected: ")
    for i, v in ipairs(selectedIngredients) do
        print(selectedIngredients)
    end
else
    print(selectedIngredients)
end

noodles.ProximityPrompt.Triggered:Connect(noodlesSelected)
tofu.ProximityPrompt.Triggered:Connect(tofuSelected)
tomato.ProximityPrompt.Triggered:Connect(tomatoSelected)
noble juniper
#

you're close! the issue is that those are all individual functions rather than more combined.

if #selectedIngredients > 0 then
    print("You selected: ")
    for i, v in ipairs(selectedIngredients) do
        print(selectedIngredients)
    end
else
    print(selectedIngredients)
end

this part only ever runs once because it's not connected to an event or any of the other functions!

obtuse prism
noble juniper
#

it could yes, technically

#

in terms of neatness/bulkiness, it's not ideal - you have a lot of repeat code currently

obtuse prism
#

Ohh I see an issue, I did what I thought would be the fix and the output keeps multiplying infintely

#

As in everytime I trigger a proximy prompt

noble juniper
#

or, you could put that if statement in a new function, and just call that at the end of each of your other functions so there's less copy/pasting

#

sorry ¯_(ツ)_/¯

obtuse prism
#

I'll try that and let you know how it goes

obtuse prism