Skip to content

Instantly share code, notes, and snippets.

@cuixin
Created July 6, 2018 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuixin/726912c882757a994340228a5ccf853f to your computer and use it in GitHub Desktop.
Save cuixin/726912c882757a994340228a5ccf853f to your computer and use it in GitHub Desktop.
lua fibonacci with closure.
local function my_ipairs(t)
local i = 1
return function()
local v = t[i]
if v then
local ii = i
i = i + 1
return ii, v
else
return nil
end
end
end
local function my_pairs(t)
local k, v
return function()
k, v = next(t, k)
if v then
return k, v
else
return nil
end
end
end
local t = {1, 2, 3, 4}
local kv = {a = 1, b = 2, c = 3, d = 4}
for k, v in my_ipairs(t) do
print(k, v)
end
for k, v in my_pairs(t) do
print(k, v)
end
for k, v in my_ipairs(kv) do
print(k, v)
end
for k, v in my_pairs(kv) do
print(k, v)
end
local function my_fibonacci(times)
local i = 1
local next_i = 1
local n = 0
return function()
local _i, _next_i = i, next_i
i = _next_i + _i
next_i = i + next_i
n = n + 1
if n <= times then
return _i, _next_i
else
return nil
end
end
end
for i, ii in my_fibonacci(20) do
print(i, ii)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment