让 Lua 像 Ruby

lua-users home
wiki

让我们给 Lua 一些 Ruby [1] 的语义。例如

;(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

--DavidManura

另请参阅

像下面这样的反向链接是杂乱的--页面标题链接已经提供了它们

某种程度上是的,但导航到它们需要点击两次而不是一次,而且不怎么显眼。如果反向链接显示在页面底部会更好。 --DavidManura


RecentChanges · preferences
编辑 · 历史
最后编辑于 2009年5月1日 下午8:24 GMT (差异)