table.Cut *new function*

Self-explanatory. I did not write this.


function table.Cut( tab, num )
	assert( type( tab ) == "table", "Bad argument #1 to table.Cut: argument type must be a table" )
	assert( type( num ) == "number", "Bad argument #2 to table.Cut: argument type must be a number" )
	assert( math.Round( num ) == num, "Bad argument #2 to table.Cut: number must be whole" )
	local t_num = table.Count( tab )
	if t_num <= num then
		return tab
	end
	repeat
		local last = table.GetLastKey( tab )
		table.remove( tab, last )
	until table.Count( tab ) <= num
	return tab
end

Holy shit, that’s so inefficient, it’s O(n²) outta nowhere when you can do this in O(n).

And it’s not gonna work correctly with tables containing anything other than sequential numeric keys (not that it makes any damn sense to use it like that).

This is a lot better version:



function table.Cut(tbl, n)
    -- Insert argument type checks here if you want to
    for i = #tbl, n+1, -1 do
        tbl* = nil
    end
    return tbl
end


I didn’t even think to make it work better, yea that does look a lot more efficient.

I didn’t write it, so…

If you didn’t write it, why post it?

It was someone else’s code that I stumbled upon, and I found it useful, so I thought I’d post it here in case someone else might find it useful or it get added to the GLua library.

Is there any harm in that? Just trying to be helpful.

Might as well have posted it here or submitted a pull request if you think it should be added.