This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
distantcam's profile picture

Linq For Lua

Started by distantcam, 20 October 2013 - 02:11 AM
distantcam #1
Posted 20 October 2013 - 04:11 AM
LINQ for Lua



LINQ (Language INtegrated Query) is a framework for processing data from an array and other sources. It uses a fluent style of method calling.

pastebin get RUZ1fbGE linq

API
Spoiler

Generators
  • fromArray(collection) – Creates an Enumerable from an array
  • fromDictionary(dictionary) – Creates an Enumerable from a dictionary
  • fromNil – Creates a blank Enumerable
  • fromIterator(iterator) – Creates an Enumerable from an iterator function
  • from(auto) – Creates an Enumerable from any of the above
Queries
  • concat(otherItems) – Concatenates this Enumerable with otherItems
  • where(predicate) – Filters this Enumerable using the predicate function
  • select(projection) – Converts items in this Enumerable using the projection
  • selectMany(projection) – Flattens list of lists by using the projection on each outer item and combining the results
  • skip(count) – Skips the number of items and returns the rest
  • take(count) – Takes only count number of items
Evaluators
  • toIterator() – Returns an iterator suitable for use in a for loop
  • toArray() – Returns the Enumerable as an array
  • dump() – Prints each item in the Enumerable

Examples
Spoiler

e = linq.from({1, 2, 3, 4, 5})
q = e:where(function(v) return v % 2 == 0 end)
q:dump()

-- Returns:
-- 2
-- 4

e:select(function(v) return v * 3 end):dump()

-- Returns:
-- 3
-- 6
-- 9
-- 12
-- 15

e:take(2):dump()

-- Returns:
-- 1
-- 2

for i in e:take(2):toIterator() do
  print(i)
end

-- Equivalent to previous statement

e:skip(2):dump()

-- Returns:
-- 3
-- 4
-- 5

The code is available on GitHub.
ElvishJerricco #2
Posted 20 October 2013 - 03:22 PM
Haven't tested this but it looks really nice. Good job. Maybe you could allow passing a custom function to dump? Like e:dump(print) or e:dump(fileHandle.writeLine), so that the dump can be put in any custom place.
distantcam #3
Posted 20 October 2013 - 07:51 PM
Ooh that's a good idea. I've added the function as an optional parameter so if it's left out it defaults to print.