LuaQ is a set of functions for manipulating iterators in a similar fashion to the popular System.Linq library in dotnet.
Include the library
local query = require('query')
Using queries
-- the identity property of querieslocalq=query{ 1, 2, 3, 4 }
-- iterate through the queryforiteminq.list() doprint(item)
end-- prints [1, 2, 3, 4]-- shorthand for printing a queryq:print() -- prints [1, 2, 3, 4]-- you can also create queries from other iteratorslocalq=query(query.range(1, 5))
q:print() -- [1, 2, 3, 4, 5]Filtering
-- to filter a query pass a predicate to the where methodfunctionisEven(value)
returnvalue%2==0endlocalq=query{1, 2, 3, 4}:where(isEven)
q:print() -- [2, 4]-- you may prefer to use anonymous functionslocalq=query{1, 2, 3, 4}:where(function (v) returnv%2==0end)
q:print() -- [2, 4]-- you can also pass lambda strings such as thislocalq=query{1, 2, 3, 4}:where('v -> v % 2 == 0')
q:print() -- [2, 4]Transforming
-- to transform or select data from an item, use the select methodlocalq=query{1, 2, 3, 4}:select('v -> v * v')
q:print() -- [1, 4, 9, 16] -- you can continue to chain together operationslocalq=query(query.range(1,10))
:select('v -> v * v')
:select('v -> tostring(v)')
:where('s -> string.len(s) ~= 2')
q:print() -- [1, 4, 9, 100] Enumeration
-- For most operations, each operation is applied once to each peice of datalocalq=query{1, 2, 3, 4}
:where(function (v)
print("First operation, " ..v)
returnv==3end)
:select(function (v)
print("Second operation, " ..v)
return"(" ..v..")"end)
q:print()
-- output:Firstoperation, 1Firstoperation, 2Firstoperation, 3Secondoperation, 3
(3) Firstoperation, 4Operations that return a new query execute only when they are enumerated. Other operations that return specific values or have to look all of the data to return the next item execute immediately.
Aggregate
-- sum a list using aggregatelocalsum=query{1, 2, 3, 4}:aggregate('value, accumulator -> value + accumulator', 0)
print(sum) -- 10localcat=query{1, 2, 3, 4}:aggregate('value, accumulator -> value .. accumulator', '')
print(cat) -- 4321First, FirstOrDefault, Single, etc
-- select first itemlocalq=query{1, 2, 3, 4}:first() -- 1localq=query{1, 2, 3, 4}:first('v -> v > 10')
Error: Noitemmatchedpredicatelocalq=query{1, 2, 3, 4}:firstOrDefault('v -> v > 10') -- nillocalq=query{1, 2, 3, 4}:single('v -> v == 1') -- 1localq=query{1, 2, 3, 4}:single()
Error: Morethan1itemmatchedpredicatelocalq=query{1, 2, 3, 4}:single('v -> v < 2 or v > 3')
Error: Morethan1itemmatchedpredicatelocalq=query{1, 2, 3, 4}:any() -- truelocalq=query{1, 2, 3, 4}:any('v -> v > 10') -- false localq=query{1, 2, 3, 4}:contains(3) -- truelocalq=query{1, 2, 3, 4}:contains("3") -- falseSkip, Take
localq=query{1, 2, 3, 4}:skip(1) -- [2, 3, 4]localq=query{1, 2, 3, 4}:take(1) -- [1]-- note, this query returns a query of length 1, not the number 1localq=query{1, 2, 3, 4}:skip(1):take(1) -- [2, 3]localq=query(query.range(1,10)):skip(2):take(1):skip(2):take(1) -- [3, 6]