让 Lua 像 Ruby 一样 |
|
;(3):times(function(x) print(x) end) hash = H{x = 1, y = 2, z = 3} hash:delete_if(function(key, value) return key == 'y' end) hash:each(function(key, value) puts(key, value) end) --[[OUTPUT: 1 2 3 x 1 z 3 --]]
它被实现为
-- This is rather incomplete but is a start. -- ruby numbers local mt = {} debug.setmetatable(0, mt) local funcs = {} function funcs.times(num, func) for i=1,num do func(i) end end mt.__index = funcs; -- ruby hash local h_mt = {} h_mt.__index = h_mt function h_mt:each(func) for k,v in pairs(self) do func(k,v) end end function h_mt:delete_if(func) for k,v in pairs(self) do if func(k,v) then self[k] = nil end end end function H(t) return setmetatable(t, h_mt) end -- ruby functions puts = print
像这样的反向链接是杂乱无章的——页面标题链接已经提供了它们