Navigating to sub table using variable?

Hi guys,
I’m wondering if it is possible to access sub table using a variable. Here is what I’m taking about:

local path = '.userSettings.keybinds'
local defaultData = {
    userSettings = {
        keybinds = {1, 2, 3}
    }
}
print(defaultData[path])

Obviously it’s just an example and it doesn’t make any sense but you got the point?

I’m half-asleep right now so this code might not be any good

local defaultData = {
	userSettings = {
		keybinds = {1, 2, 3}
	}
}

local function getSubtable(root, path)
	local locations = path:split('.')
	
	local function indexSub(toFind)
		local sub = root[toFind]
		if sub then
			return sub
		end
		
		error('No subtable called ' .. toFind)
	end
	
	for i, v in locations do
		root = indexSub(v)
	end
	return root
end

print(getSubtable(defaultData, 'userSettings.keybinds'))

This just parses the path and divides it into the locations its gonna try to find, and then goes from the root (in this case defaultData) to the desired value in it recursively

1 Like

I literally got out of bed to test it :joy:. Works perfectly fine! However i thought that there was a simpler way of doing this but i guess there is no. Thank you very much!

1 Like