讓 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


最新變更 · 首頁
編輯 · 歷史
上次編輯時間為 2009 年 5 月 2 日,格林威治標準時間早上 2 點 24 分 (diff)