[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: using a closure for enumerating table
- From: jseb <gmane2010@...>
- Date: Sat, 16 Jun 2012 12:58:56 +0200
Hello,
I try to print elements of this table:
local big =
{ foo = { "sub1_foo","sub2_foo" },
bar = { "sub1_bar", "sub2_bar" }
}
I'd like to get elements in this format:
"foo","sub1_foo"
"foo","sub2_foo"
"bar","sub1_bar"
"bar","sub2_bar"
So, i've thought it was a nice day to write a closure.
But the closure always returns the same thing ("bar" with it first element).
I know i have the same problem with tables without embedded tables, but
on those tables, you probably told me to use «for i,v in pairs(t)…».
That's why i've made made it more difficult.
And i like to solve it with a closure.
Please, have a look:
#!/usr/bin/env lua
local big =
{ foo = { "sub1_foo","sub2_foo" },
bar = { "sub1_bar", "sub2_bar" }
}
function iter (t)
return function()
for k,v in pairs(t) do
for sk,sv in pairs(v) do
print (k .. " -> " .. sv)
return k,sv
end
end
end
end
fx=iter(big)
fx() -- «bar -> sub1_bar»
fx() -- «bar -> sub1_bar» (again)
-- i didn't use «for i,v in iter(big)» because of infinite loop
#end of Lua sample
Thank you.