Get value with number index in a table of string indexes

Let’s say if i have a table with string indexes, and i want to get a value with a number index, how would you do this?

Like for example:

local a = {["a"] = "rofl", ["b"] = "lol"}
print(a[1]) --Prints nil

This does not work. Is there a simple way to make this work?

Here’s one option:

local a = {["a"] = "rofl", ["b"] = "lol"}

function IndexDictionary(dictionary,index)
	local i = 0
	for _,value in pairs(dictionary) do
		i=i+1
		if i == index then
			return value
		end
	end
end

print(IndexDictionary(a,1))

And here’s another:

local a = {["a"] = "rofl", ["b"] = "lol"}
local a2 = {}

for _,value in pairs(a) do
	table.insert(a2,value)
end

print(a2[1])

But the first is probably better.

But for what reason are you trying to index a dictionary via a number?

1 Like

I need this function where the structure is like this:

local layerModule.table = { --THIS TABLE MUST BE ORDERED FROM LOWEST DEPTH TO HIGHEST DEPTH!!!
	["shallow"] = {
		layerColor = Color3.fromRGB(99, 95, 98),
		layerMaterial = Enum.Material.Slate,

		bigCaves = {1.15, 90, 2, 0.5},
		smallCaves = {0.97, 50, 1, 0.5},

		minDepth = 0,
		maxDepth = 100,

		ignoreOres = {"dirt", "grass"},
	},
	["medium"] = {
		layerColor = Color3.fromRGB(66, 63, 65),
		layerMaterial = Enum.Material.Slate,

		bigCaves = {1.15, 90, 2, 0.5},
		smallCaves = {0.97, 50, 1, 0.5},

		minDepth = 100,
		maxDepth = 300,

		ignoreOres = {"dirt", "grass"},
	}
}

Where i need the current and next value a number “is in”. (calculated with minmax depth)

The order and the IndexDictionary function could be non-deterministic. You shouldn’t rely on a behavior that is expliticly undefined.


You could either hardcode the keys in a table as an array, or you could create a new array then iterate the old table but disregarding the order and then do an ordered insertion to the new table. Then you could use that array as the key in that case.