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

How do I get the first Key and Value in an array?

I know I can do this to get each Key and Value in an array, but how do I only get the first?

A dictionary kind of array.

local Array = {
	["Entry1"] = {1,2,3},
	["Entry2"] = {4,5,6}
}

for k, v in pairs(Array) do
	return k, v
end

I need it to only return the first key and value

3 comments

0

Arrays and dictionnaries are complete opposites. Besides, there's no such thing as an 'array' or a 'dictionnary' in Lua. Those are just concepts people came up with. You're thinking of a 'table' with string keys.

0

You could just do Array["Entry"..num] if you're naming all of 'em consistently like that.

0

Well the entry names are random so I wouldn't know the string to index them with.

3 answers

✓ Accepted answer

You can use the standard next Lua function for this.

local t = {
    ["Entry1"] = { 1, 2, 3 },
    ["Entry2"] = { 4, 5, 6 }
}


local key, value = next(t)

print(key, value)

Please note, however, that the order of the keys of a dictionnary-formatted table are undefined. Meaning "Entry1" and its value will not necessarily come out before "Entry2" and its associated value.

3 comments

0

I ran this and it actually outputs Entry2 as the key.

0

@IDidMakeThat Yeah, I totally forgot to mention that. 'Was editing as you commented, lol.

0

Thanks, this works for me. I just needed a random entry out of my array, as any of the entries would work for my application.

local k,v = 1, Array[1]

I recommend you add some lines to check if Array is empty or not, can simply be done with the #operator .

1 comment

0

I mean an array like a dictionary, sorry forgot to add that

There's not really a good way to do this, as the order in which indices are traversed by the next () and pairs() function is undefined. For example,

local Table = {
	x = 1,
	y = 2,
	z = 3
}

for k, v in pairs(Table) do
	print(k, v)
end

might output:

	y	2
	x	1
	z	3

Therefore, there's no easy way to tell which key-value pair is the first one (as far as I know).

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