Log In  

Yo @zep,

This thread isn't the first time I've seen people ask about inserting values into the middle or start of arrays/sequences:

https://www.lexaloffle.com/bbs/?tid=38249

It occurs to me that a lot of carts probably have similar boilerplate code like the ins() function I wrote for that person. I think it would be nice, and better for PICO-8's host-machine performance, if there were a C-side implementation of that insert code, and I think you could do it simply by taking an optional third argument to add(), effectively implementing something like this Lua code on the C side:

function add(t,v,i)
  i=i or #t+1 -- default to extending the list
  for j=#t,i,-1 do
    t[j+1]=t[j]
  end
  t[i]=v
  return v -- return the added value for convenience
end

This shouldn't break any existing code, since there hasn't previously been a third arg, and the default value produces the existing behavior.

(Come to think of it, I'm not sure if you have add() on the C side or as hidden Lua. If it's not already on the C side, you might want to put it there, because it happens a lot in carts and doing it through interpreted code is definitely going to slow things down on the host hardware. Same goes for any other oft-called hidden Lua code.)

P#77570 2020-06-03 00:18 ( Edited 2020-06-03 00:23)


[Please log in to post a comment]