Missing support for table.maxn()?

Hi everybody! I'm having a blast porting some hobby projects to the Playdate. In doing so I ran into an issue - I've been using table.maxn() to get the last integer key from a table (since the table is sparse, I would run into bugs if I used #table ), and I got the error "field 'maxn' is not callable (a nil value)". assert( table.maxn ) does indeed give an error, whereas assert( table.sort ) for example works fine.

Is there a way to call table.maxn() that I am missing, and if there isn't - is there a way for me to get the largest integer index of a sparse table without iterating through all the elements using eg. pairs() ?

In a normal Lua environment, I would expect these outputs:

local newTable = { "a", "b", "c", [8] = "h", [112] = "q", [873] = "x" }
print( table.maxn( newTable ) ) -- prints 873
print( #newTable ) -- prints 8

table.maxn was deprecated in lua 5.2 (ref)

  • Function table.maxn is deprecated. Write it in Lua if you really need it.
1 Like

Ah well that explains it!

I'm using the following in case someone else finds it useful - pairs() does not necessarily loop through integer keys in ascending order, so you need to check for what the max value is.

table.maxn = function( tableObject )
	local maxIndex = 0
	for k, _ in pairs( tableObject ) do
		maxIndex = math.max( maxIndex, k )
	return maxIndex