Created
July 6, 2018 03:07
-
-
Save cuixin/726912c882757a994340228a5ccf853f to your computer and use it in GitHub Desktop.
lua fibonacci with closure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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