Skip to content

Instantly share code, notes, and snippets.

@randrews
Created July 24, 2011 05:34
Show Gist options
  • Save randrews/1102289 to your computer and use it in GitHub Desktop.
Save randrews/1102289 to your computer and use it in GitHub Desktop.
Array library for Lua
function string.ordinalize(str)
local num = tonumber(str)
local endings = {"st", "nd", "rd"}
if num >= 11 and num <= 13 then
return num .. "th"
elseif num % 10 > 0 and num % 10 <= #endings then
return num .. endings[num % 10]
else
return num .. "th"
end
end
_array = {
each =
function(list, fn, ...)
local r = array()
for k,v in pairs(list) do
r[k] = fn(v, ...)
end
return r
end,
send =
function(msg)
return function(list, ...)
local function fn(v, ...)
return (v[msg])(v, ...)
end
return _array.each(list, fn, ...)
end
end,
__index =
function(t, name)
if name == 'each' then return _array.each
else return _array.send(name) end
end,
__tostring =
function(tbl)
local strings = tbl:each(tostring)
return '[' .. table.concat(strings, ', ') .. ']'
end
}
function array(...)
return setmetatable({...}, _array)
end
A = array
----------
print(A(1,2,3,4):each(function(x) return x*x end))
print(A(1,10,33):each(tostring):ordinalize())
print(A('foo','bar','baz'):sub(1,1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment