pmgl / microstudio

Free, open source game engine online
MIT License
931 stars 106 forks source link

Suggestion: Advanced List indexing options #83

Closed TinkerStudio closed 2 years ago

TinkerStudio commented 2 years ago

It has been suggested to add more indexing options for lists.
Here an example from Python: Indexing in Python

pmgl commented 2 years ago

I looked into it a bit ; some of these features (like reverse indexing) are not easily possible without breaking the current List model in microScript which is very close to JavaScript arrays (and based on them). I think the other features (like slicing) are already covered by List functions in microScript (or let me know and they will!). I do not see a great benefit in adding more syntax options for it.

But wait! Here is something that should interest you: microScript 2.0 allows you to add your own custom functions or operators for lists, strings and functions:

Example:

List.get = function(index)
  this[if index<0 then length+index else index end]
end

List."%" = function(list,length)
  list.slice( 0 , length )
end

With that defined, you can now do:

[1,2,3,4,5,6,7,8].get(-1)     // index elements from the end
8

[1,2,3,4,5,6,7,8] % 4         // get a sub-list of the list
[1,2,3,4]

While we are here, let's do something crazy :-) Python has this my_list[start_index:end_index:step_size], in microScript we could mimic it with this code:

List."|" = function(list,arg)
  local start_index = arg[0]
  local end_index = arg[1]
  local step = arg[2]
  local res = []
  for i=start_index to end_index by step
    res += list[i]
  end
  res
end

List.range = function(num) // let's also create our version of range(100)
  local res = []
  for i=0 to num-1 by 1
    res += i
  end
  res
end

Now that this is set, we can do:

List.range(100)|[12,84,3]
[12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84]
TinkerStudio commented 2 years ago

That surpasses the original request by miles :)
Loving it ❤️