/ Published in: Lua
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
require "std.table" -- For memoize function map(t, f) local nt = table.memoize(function (k) return f(t[k]) end) local mt = getmetatable(nt) function mt:__pairs() local k local function mynext() k,v = next(t, k) if k == nil then return nil end return k,nt[k] end return mynext, self end return nt end require "std.base" -- For better table tostring() local mylist = {1,3,5,7,9} local newlist = map(mylist, function(v) return 3 * v - 2 end) assert(mylist[3] == 5) assert(newlist[3] == 13) require "std.base" -- For the pairs() that obeys the __pairs metamethod print("old:", mylist) print("new(3*v-2):", newlist)