Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I reference the "original" key/value pair in a recursive function?

Asked by
Trew86 175
5 years ago
Edited 5 years ago

I have a my function called tableRec. I added the level variable with the help of len_ny. However it seems the script still won't distinguish the levels of recursion, as the output doesn't print when the level 3 has been reached, and trackPoint remains as nil, causing an error.

module.tableRec = function(tab, func)
if type(tab) ~= "table" then return end
local level = 0;
for i, v in pairs(tab) do
level = level + 1
func(i, v, level)
module.tableRec(v, func, level)
end
end 


functions.tableRec(module, function(a, b, lvl)
local trackPoint
if lvl == 3 then
print("level 3 of recursion has been reached")
trackPoint = b
end
if a == "Sensor" then
functions.tableRec(module, function(i, v, level)
local adjacentBlock
if level == 1 then
adjacentBlock = v
end
if i == "Sensor" then
if v == trackPoint.Sensor then
trackPoint.Adjacent = adjacentBlock
end
end
end)
elseif a == "PathOptions" then
for i = 1, #b do
b[i].Status = Instance.new("IntValue")
end
end
end)

1 answer

Log in to vote
1
Answered by
len_ny 8
5 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.
module.tableRec = function(tab, func)
if type(tab) ~= "table" then return end
    local level = 0;
    for i, v in pairs(tab) do
        level = level + 1
        func(i, v, level)
        module.tableRec(v, func, level)
    end
end

functions.tableRec(module, function(a, b, lvl)
    if lvl == 2 then
        print('level 2 of recursion reached !!')
    end

    if a == "PathOptions" then
        for i = 1, #b do
            b[i].Status = Instance.new("IntValue")
        end
    end
end)

its pretty simple but i could see how it could be a problem, good luck on your adventures!

0
Wow, i refrained from doing that at first because I thought it would make a new "level" variable for each table it went through. Thanks! Trew86 175 — 5y
Ad

Answer this question