Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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!

1 comment

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.