We Recommend

PIC Basic: Programming and Projects PIC Basic: Programming and Projects
The simplest quickest way to get up and running with microcontrollers. makes the PC accessible to students and enthusiasts. The practicalities of programming and the scope of using a PIC are then explored through 22 wide ranging electronics projects.


Posted By

kergoth on 12/18/06


Tagged

tables map lua metatables


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

lenn0x


Lua: Lazy Map Implementation: Round One


Published in: Lua 


  1. require "std.table" -- For memoize
  2.  
  3. function map(t, f)
  4. local nt = table.memoize(function (k) return f(t[k]) end)
  5. local mt = getmetatable(nt)
  6. function mt:__pairs()
  7. local k
  8. local function mynext()
  9. k,v = next(t, k)
  10. if k == nil then return nil end
  11. return k,nt[k]
  12. end
  13. return mynext, self
  14. end
  15. return nt
  16. end
  17. require "std.base" -- For better table tostring()
  18.  
  19. local mylist = {1,3,5,7,9}
  20. local newlist = map(mylist, function(v) return 3 * v - 2 end)
  21. assert(mylist[3] == 5)
  22. assert(newlist[3] == 13)
  23.  
  24. require "std.base" -- For the pairs() that obeys the __pairs metamethod
  25. print("old:", mylist)
  26. print("new(3*v-2):", newlist)

Report this snippet 

You need to login to post a comment.