Skip to content

Instantly share code, notes, and snippets.

@johnbartholomew
Created February 3, 2013 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbartholomew/4699869 to your computer and use it in GitHub Desktop.
Save johnbartholomew/4699869 to your computer and use it in GitHub Desktop.
function numbered_keys(step, context, position)
local k = position
local f = function(s, i)
local v
k,v = step(s, k)
if k ~= nil then
return (i+1), v
end
end
return f, context, 0
end
function filter(predicate, step, context, position)
local f = function (s, k)
local v
repeat k,v = step(s,k); until (k == nil) or predicate(k,v)
return k,v
end
return f, context, position
end
function map(transformer, step, context, position)
local f = function (s, k)
local v
k, v = step(s, k)
if k ~= nil then
return transformer(k,v)
end
end
return f, context, position
end
function build_array(f, s, k)
local v
local t = {}
while true do
k, v = f(s, k)
if k == nil then break end
table.insert(t, v)
end
return t
end
function build_table(f, s, k)
local v
local t = {}
while true do
k, v = f(s, k)
if k == nil then break end
t[k] = v
end
return t
end
local t = {
name = 'names',
description = 'Names of People',
'john',
'paul',
'george',
'ringo',
'bert',
}
print('pairs:')
for k,v in pairs(t) do print(k,v); end
print('\nnumbered:')
for k,v in numbered_keys(pairs(t)) do print(k,v); end
print('\nfiltered:')
for k,v in filter(function(k,v) return type(k) == 'number' and k < 3; end, pairs(t)) do print(k,v); end
print('\nmapped:')
for k,v in map(function(k,v) return k,v .. '!'; end, pairs(t)) do print(k,v); end
print('\nrebuilt:')
local t2 = build_array(filter(function(k,v) return k < 3; end, ipairs(t)))
for i = 1, #t2 do
print(i, t2[i])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment