Reverse of table.maxn()

Hello, I am trying to find a function that is the opposite of table.maxn().
Current table.maxn() returns the maximum numeric key of the provided table,
ex. {100,200,300,400} Returns: 400

I want something that does the reverse or opposite, I didn’t find a function for this under the table documentation, any recommendations?

To be clear in my example context this function should return 100

I already tried table[1] which returns nil because the first table value is 100

math.min(table.unpack(urtable))

This is incorrect. table.maxn on that table would return 4.

There is not a built-in way to do the opposite of this, but it can be easily implemented as:

local function min_key(tbl)
	local min
	for key in tbl do
		if type(key) == 'number' and (not min or key < min) then
			min = key
		end
	end
	return min
end

Now if you wanted to get the smallest value (not key), the function can be modified as:

local function min_value(tbl)
	local min
	for _, value in tbl do
		if type(value) == 'number' and (not min or value < min) then
			min = value
		end
	end
	return min
end

The response of the user above can only work if you can guarantee the table will only have numeric values. Else, min_value is the generic solution.

Sorry I completely messed up what I was saying
For my example I got 400 because I have the table set up like this:
{
[100] = “a”,
[200] = “b”,
[300] = “c”,
[400] = “d”,
]
but I still would like something that would return 100 which is the opposite of maxn

In this case, my min_key would be the solution.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.