Log In  


On the latest episode of his advanced shmup tutorial, @Krystman showed off a function for splitting a string into a 2D array, and then said there could be more ways to make it more compact and token-efficient. Guess what I... didn't do?

Well, I didn't make it more token-efficient - my new version is close to double that of the original 28-token function at 55 tokens - but I DID make it more versatile; It can now handle:

  • 3,4,5 and onwards dimensional arrays (the original could only do 2-dimensional arrays)
  • Any character for use as a separator (the original could only use "|" and ",")
  • Optional tonum() conversion (the original had that forced on)

In fact, you could use this function exclusively instead of the built-in split() and you might not even notice. In order to get multi-dimensional arrays, the sep parameter should be given a string that is more than a single character long, with the most significant separator characters coming first. Oh, uh, after you paste the function into your code, that is. Speaking of which...

function splitf(str,sep,tnm)
 local cnt=type(sep)=="string" and #sep>1
 local arr=split(str,sep,not cnt and tnm!=false)
 if cnt then
  for k,v in pairs(arr) do
   arr[k]=splitf(v,sub(sep,2),tnm)
  end
 end
 return arr
end

if you want to get a good idea of how it behaves, paste the function definition into an empty cart, and then follow it up with this testing snippet:

function recursive_print(t,d)
 d=d or 0
 for k,v in pairs(t) do
  for i=1,9 do flip() end
  ?"\f2\*"..d.."|\fb"..k.."\f7: \fc"..tostr(v).."\f6 ("..type(v)..")"
  if type(v)=="table" then
   if d<8 then
    recursive_print(v,d+1)
   else
    ?"\f2\*"..1+d.."|\f8[ ** max depth reached ** ]"
   end
  end
 end
end

cls()
?"printing split string",13
recursive_print(splitf("1,2,3|1,2,3|1,2,3 1,2,3|1,2,3|1,2,3 1,2,3|1,2,3|1,2,3"," |,",true))

Of course, I'm sure I'm not the first person to come up with this function, and it's probably overkill in most cases. Still, if anyone wants to mess around with the function and make it more token-efficient, then I'll leave off by saying that the cnt local variable is the variable that determines if a recursive function call is necessary. (cnt for 'continue'. Previously I went with lst for 'last', but the continue flag was better at capturing the nuances of what happens when you give split() a non-string value for its separator.)

1


1

Sweet! Well done!



[Please log in to post a comment]