Lua nested coroutines - lua

I am trying to use the redis-lua library within copas. It requires some patching.
One problem is that redis-lua defines some iterators as coroutines, but these iterators perform network operations that can yield.
So, coroutine.yield is used for two very different things: for the iterator, and for copas. As network calls are nested within iterators, network yields are intercepted by the coroutine.wrap of the iterator, instead of being intercepted by copas.
The example below shows the problem :
local function iterator ()
for i = 1, 2 do
if i == 2 then coroutine.yield () end -- network yield
coroutine.yield () -- iterator yield
end
end
local citerator = coroutine.wrap (iterator)
local function loop () -- use of the iterator within a copas thread
while citerator () do end
end
local cloop = coroutine.create (loop)
while coroutine.resume (cloop) do end -- same as copas loop, executes the cloop thread
Is there a "standard" solution to this problem, still allowing to use coroutines for iterators?
I was able to make a small example work by "tagging" the yields (see below), but it is incompatible with existing code. I can leave the copas code unmodified, but have to update iterators in redis-lua.
local function wrap (f, my_tag)
-- same as coroutine.wrap, but uses my_tag to yield again
local co = coroutine.create (f)
return function ()
local t = table.pack (coroutine.resume (co))
local code = t [1]
local tag = t [2]
table.remove (t, 1)
table.remove (t, 1)
if tag == nil then
return
elseif my_tag == tag then
return table.unpack (t)
else
coroutine.yield (tag, table.unpack (t))
end
end
end
local Iterator = {} -- tag for iterator yields
local Network = {} -- tag for network yields
local function iterator ()
for i = 1, 2 do
if i == 2 then coroutine.yield (Network, i) end
coroutine.yield (Iterator, i)
end
end
local citerator = wrap (iterator, Iterator)
local function loop ()
while citerator () do end
end
local cloop = wrap (loop, Network)
while cloop () do end
Is there a better solution?

Lua coroutine always yield to the last thread they were resumed from. The Copas socket functions expect to yield back to the Copas event loop, but instead they get stuck with the coroutine used to implement the redis-lua iterators. Unfortunately there isn't much you can do to fix that except changing the code of the redis-lua iterators. The reason why no one has done so yet is that until Lua 5.2 (LuaJIT can do it as well) it wasn't even possible to yield from an iterator function (the iterator yields in redis-lua work fine because they never leave the iterator function, but you cannot yield beyond the for loop like the Copas socket functions would try to do).
Your idea about using a tag value for distinguishing the iterator yields from the rest is good. You just have to make sure that you pass all yields not intended for the iterator function to the coroutine one level up, including any arguments/return values of coroutine.yield and coroutine.resume (the later is implicit when calling the coroutine.wraped function).
More specifically, if you have code like this in redis-lua:
-- ...
return coroutine.wrap( function()
-- ...
while true do
-- ...
coroutine.yield( some_values )
end
end )
You change it to:
-- ...
local co_func = coroutine.wrap( function()
-- ...
while true do
-- ...
coroutine.yield( ITERATOR_TAG, some_values ) -- mark all iterator yields
end
return ITERATOR_TAG -- returns are also intended for the iterator
end )
return function()
return pass_yields( co_func, co_func() ) -- initial resume of the iterator
end
The ITERATOR_TAG and the pass_yields function go somewhere near the top of redis.lua:
local ITERATOR_TAG = {} -- unique value to mark yields/returns
local function pass_yields( co_func, ... )
if ... == ITERATOR_TAG then -- yield (or return) intended for iterator?
return select( 2, ... ) -- strip the ITERATOR_TAG from results and return
else
-- pass other yields/resumes back and forth until we hit another iterator
-- yield (or return); using tail recursion here instead of a loop makes
-- handling vararg lists easier.
return pass_yields( co_func, co_func( coroutine.yield( ... ) ) )
end
end
AFAIK, the redis-lua developers are planning to tag another release by the end of the year, so they probably will be grateful for pull requests.

In your first example, you are using wrap(loop). I suppose this is copas' wrap, because there is no reference to copas in this code...
However, you are supposed to copas.wrap() a socket, but your loop is a function!
See copas documentation for a good introduction.

Related

Trying to understand Custom Iterators

im trying to understand the iterators, in many examples I founf something like this:
function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0 // why not return square(iteratorMAxCount,0)????
end
for i,n in squares(3)
do
print(i,n)
end
First I dont understand the line I comment, and I dont find an easy example of how to do a Stateful Iterator and a Stateless iterator. Can anybody help me? thanks
From Lua Reference Manual 3.3.5:
A for statement like
for var_1, ···, var_n in explist do block end is equivalent to the code:
do
local f, s, var = explist
while true do
local var_1, ···, var_n = f(s, var)
if var_1 == nil then break end
var = var_1
block
end
end Note the following:
explist is evaluated only once. Its results are an iterator function,
a state, and an initial value for the first iterator variable. f, s,
and var are invisible variables. The names are here for explanatory
purposes only. You can use break to exit a for loop. The loop
variables var_i are local to the loop; you cannot use their values
after the for ends. If you need these values, then assign them to
other variables before breaking or exiting the loop.
So squares() has to return a function (square) a state (iteratorMaxCount) and an initial value (0) in order to work with a generic for loop.
Read the reference manual, Programming in Lua.

Lua and serialized closures

I'm trying to serialize and deserialize a Lua closure
my basic understanding is that the below factory should generate closures (and that Lua doesn't much distinguish between functions and closures -- i.e. there is no type 'closure')
> function ffactory(x) return function() return x end end
> f1 = ffactory(5)
> print(f1())
5 <-- so far so good
> s = string.dump(f1)
> f2 = load(s)
> print(f2())
table: 00000000002F7BA0 <-- expected the integer 5
> print(f2()==_ENV)
true <-- definitely didn't expect this!
I expected the integer 5 to be serialized with f1. Or, if string.dump can't handle closures, i expected an error.
I get quite different (but more what I expected) results with a mild change. It looks like f2 is indeed a closure, but string.dump didn't attempt to serialize the value of x at the time it was serialized.
The docs don't help me much. (what do they mean by "...with new upvalues"?)
> function ffactory(x) return function() return x+1 end end
> f1 = ffactory(5)
> print(f1())
6 <-- good
> s = string.dump(f1)
> f2 = load(s)
> print(f2())
stdin:1: attempt to perform arithmetic on upvalue 'x' (a table value)
stack traceback:
stdin:1: in function 'f2'
stdin:1: in main chunk
[C]: in ?
You can do something like this to save/restore those upvalues (note it doesn't handle upvalues shared between different functions):
local function capture(func)
local vars = {}
local i = 1
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
vars[i] = value
i = i + 1
end
return vars
end
local function restore(func, vars)
for i, value in ipairs(vars) do
debug.setupvalue(func, i, value)
end
end
function ffactory(x) return function() return x end end
local f1 = ffactory(5)
local f2 = (loadstring or load)(string.dump(f1))
restore(f2, capture(f1)) --<-- this restored upvalues from f1 for f2
print(f1(), f2())
This works under both Lua 5.1 and Lua 5.2.
Note an interesting result if you change ffactory slightly (added math.abs(0); anything that uses global table in any way will do):
function ffactory(x) return function() math.abs(0) return x end end
Now if you restore upvalues you get the same result, but if you don't restore upvalues you get a run-time error under Lua 5.2:
lua.exe: upvalues.lua:19: attempt to index upvalue '_ENV' (a nil value)
stack traceback:
upvalues.lua:19: in function 'f2'
upvalues.lua:24: in main chunk
[C]: in ?
the docs are pretty clear. string.dump doesn't handle closures using upvalues. this is because the upvalues could be anything (including userdata, and how would Lua know how to serialize that?)
upvalues are the external variables that are local to a function due to scoping/closures. since x in your example is an upvalue to the function returned by ffactory, it does not get serialized.
if you want to support this somehow, you would have to store the upvalues yourself and set them again after you've deserialized the function, like this:
function ffactory(x)
return function() return x+1 end
end
local f1 = ffactory(5)
print(f1())
local s = string.dump(f1)
f2 = loadstring(s)
debug.setupvalue(f2, 1, 5)
print(f2())

Create Lua function from string

I am creating functions (of x) from a string in Lua. The code I am using is
function fcreate(fs)
return assert(loadstring("return function (x) return " .. fs.." end"))()
end
This works for globals, e.g.
u=fcreate("math.sin(x)")
does the right thing.
However, it does not seem to like local variables. So
local c=1
u=fcreate("math.sin(x)+c")
will not work because c is local.
Is this fixable?
"loadstring does not compile with lexical scoping", so no, it can't see locals outside the loadstring call.
Is this fixable?
That depends. Why are you using loadstring in the first place? Lua supports closures as first class values, so I can't see from your example why you'd need loadstring.
Your example:
u = fcreate("math.sin(x)+c")
Can be rewritten without the need for loadstring or your fcreate function:
u = function(x) return math.sin(x)+c end
Which of course is the same as:
function u(x) return math.sin(x) + c end
I can see a case for loadstring if you have user-configurable expressions that you wanted to compile into some other function, but your case with the local c suggests that's not the case. Are you trying to make some kinda of home-rolled lamda syntax?
Can't be done in any reasonable way. For an example of why, look at this:
function makefunction(name)
local a = 1
local b = 2
local c = 3
-- ...
return assert(loadstring("return " .. name))
end
local a = 4
local func = makefunction("a")
print(func())
If this worked, what is printed? 1 or 4? Does it capture the variable from the place where the function was loaded, even though that function doesn't exist anymore? Or does it look it up from the place where it was called?
The first would mean that the function is lexically scoped wherever it's created. Being able to access the variable after the function has exited means that the variable would need to be promoted into an upvalue dynamically, which is not something that Lua can do at the moment. As it is now, Lua can see every access to a local variable during compilation, so it knows which variables to turn into upvalues (at a performance hit) and which to keep as locals.
The second would mean that variable accesses inside a loadstring'd function would work completely different than every other access in Lua: Lua uses lexical scoping, not dynamic scoping. It'd be a huge implementation change in Lua, and an extremely inconsistent one.
So, neither is supported. You can control the environment of a dynamically loaded function, using setfenv in Lua 5.1 or the env parameter of load(...) in Lua 5.2, but neither of those let you access local variables automatically.
Something you could do if you don't need to mutate the local variables is to pass those values as arguments to the generated function. You would still need to manually specify the variables to close over but its better then nothing.
For example, you can build up your closure to look like
return (function(a,b,c)
return function(x) return print(a, x) end
end)(...)
We might do that by changing your function to look like
function fcreate(variables, fs)
local varnames = {}
local varvalues = {}
local nvars = 0
for n,v in pairs(variables) do
nvars = nvars + 1
table.insert(varnames, n)
table.insert(varvalues, v)
end
local chunk_str = (
'return (function(' .. table.concat(varnames, ',') .. ') ' ..
'return function(x) return ' .. fs .. ' end ' ..
'end)(...)'
)
return assert( loadstring(chunk_str) )( unpack(varvalues, 1, nvars) )
end
local a = 1;
local f = fcreate({a=a}, 'x+a')
print(f(1), f(2))

What's the difference between these two Lua examples? Is one better?

I'm just getting started with Lua. In the example I'm learning from (the Ghosts & Monsters Corona open source), I see this pattern repeatedly.
local director = require("director")
local mainGroup = display.newGroup()
local function main()
mainGroup:insert(director.directorView)
openfeint = require ("openfeint")
openfeint.init( "App Key Here", "App Secret Here", "Ghosts vs. Monsters", "App ID Here" )
director:changeScene( "loadmainmenu" )
return true
end
main()
Is this some sort of convention experienced Lua programmers recommend or are there genuine advantages to doing it this way? Why wouldn't you just skip the function all together and do this:
local director = require("director")
local mainGroup = display.newGroup()
mainGroup:insert(director.directorView)
local openfeint = require ("openfeint")
openfeint.init( "App Key Here", "App Secret Here", "Ghosts vs. Monsters", "App ID Here" )
director:changeScene( "loadmainmenu" )
Is there some implicit benefit to the first style over the second? Thanks!
Is this some sort of convention experienced Lua programmers recommend or are there genuine advantages to doing it this way?
It's not typical. The advantage is that object state is private, but that's not enough of an advantage to recommend it.
I see this pattern repeatedly.
I've never seen it before, and it happens only once in the source you posted.
EDIT: Adding a response to a question asked in the comments below this post.
A function which accesses external local variables binds to those variables and is called a 'closure'. Lua (for historical reasons) refers to those bound variables as 'upvalues'. For example:
local function counter()
local i = 1
return function()
print(i)
i = i + 1
end
end
local a, b = counter(), counter()
a() a() a() b() --> 1 2 3 1
a and b are closures bound to different copies of i, as you can see from the output. In other words, you can think of a closure as function with it's own private state. You can use this to simulate objects:
function Point(x,y)
local p = {}
function p.getX() -- syntax sugar for p.getX = function()
return x
end
function p.setX(x_)
x = x_
end
-- for brevity, not implementing a setter/getter for y
return p
end
p1 = Point(10,20)
p1.setX(50)
print(p1.getX())
Point returns a table of closures, each bound to the locals x and y. The table doesn't contain the point's state, the closures themselves do, via their upvalues. An important point is that each time Point is called it creates new closures, which is not very efficient if you have large quantities of objects.
Another way of creating classes in Lua is to create functions that take a table as the first argument, with state being stored in the table:
function Point(x,y)
local p = {x=x,y=y}
function p:getX() -- syntax sugar for p.getX = function(self)
return self.x
end
function p:setX(x)
self.x = x
end
return p
end
p1 = Point(10,20)
p1:setX(50) -- syntax sugar for p1.setX(p1, 50)
print(p1:getX()) -- syntax sugar for p1.getX(p1)
So far, we're still creating new copies of each method, but now that we're not relying on upvalues for state, we can fix that:
PointClass = {}
function PointClass:getX() return self.x end
function PointClass:setX(x) self.x = x end
function Point(x,y)
return {
x = x,
y = y,
getX = PointClass.getX,
setX = PointClass.getY,
}
end
Now the methods are created once, and all Point instances share the same closures. An even better way of doing this is to use Lua's metaprogramming facility to make new Point instances automatically look in PointClass for methods not found in the instance itself:
PointClass = {}
PointClass.__index = PointClass -- metamethod
function PointClass:getX() return self.x end
function PointClass:setX(x) self.x = x end
function Point(x,y)
return setmetatable({x=x,y=y}, PointClass)
end
p1 = Point(10,20)
-- the p1 table does not itself contain a setX member, but p1 has a metatable, so
-- when an indexing operation fails, Lua will look in the metatable for an __index
-- metamethod. If that metamethod is a table, Lua will look for getX in that table,
-- resolving p1.setX to PointClass.setX.
p1:setX(50)
This is a more idiomatic way of creating classes in Lua. It's more memory efficient and more flexible (in particular, it makes it easy to implement inheritance).
I frequently write my own Lua scripts this way because it improves readability in this case:
function main()
helper1( helper2( arg[1] ) )
helper3()
end
function helper1( foo )
print( foo )
end
function helper2( bar )
return bar*bar
end
function helper3()
print( 'hello world!' )
end
main()
This way the "main" code is at the top, but I can still define the necessary global functions before it executes.
A simple trick, really. I can't think of any reason to do this besides readability.
The first style could be used too improove readability, but I would rather give the function some meaningful name instead of main or just go without the function.
By the way, I think it's always a good practice to name blocks of code, i.e. put them into functions or methods. It helps explain your intend with that piece of code, and encourages reuse.
I don't see much point to the first style as you've shown it. But if it said something like if arg then main() end at the bottom, the script might (just might) be useful as a loadable "library" in addition to being a standalone script. That said, having a main() like that smacks of C, not Lua; I think you're right to question it.

Functions in a Table - Lua

I have a table that has multiple functions in it. I'm trying to write a single function that will go through and use all the functions by passing random information into it.
Methods = {}
insert functions into Methods Table
function Methods:Multi() if #self > 0
then .........................
I'm guessing i need a loop that goes through the entire table but I can't do #self because i need it to do each function multiple times. Not sure how to pass in random info to the function either. Any help would be appreciated
Your problem doesn't seem to be all that specific - you're likely going to need to define exactly what you want to happen in more detail in order to be able to implement a program for it. (Sort of like if you told me "I need a program that calculates a number" - I'd probably respond "okay, what number do you want it to calculate?"
Things to consider:
Exactly how many times do you want to call each function? Will this be the same for each function? Will it vary?
If the number of calls varies, what should determine this?
How exactly do you want to determine what parameters are passed? Their types/count? Their values?
A very basic starting framework might look like this:
Methods = {}
-- Insert functions into Methods table
for _,func in ipairs(Methods) do
for i=1,5 do
func()
end
end
which would call each function 5 times, albeit w/o arguments.
I modified the above suggestion to
function CallFuncs(times, funcs, ...)
while (times > 0) do
for _, func in pairs(funcs) do
func(...)
end
times = times - 1
end
end
Example usage:
t = {
function( n ) print( n ) end,
function( n ) print( #n ) end,
}
CallFuncs( 2, t, 'foo' )
yields
foo
3
foo
3
Try this:
function CallFuncs(times, funcs, ...)
for i=1,times do
for _, func in pairs(funcs) do
if type(...) == "table" then func(unpack(...)) else func(...) end
end
end
end
Usage:
local t = {
function(n) print(n) end,
function(n) print(n+1) end,
function(n) print(n+2) end
}
CallFuncs(3, t, 2)
This assumes all the functions in the table have more or less the same arguments.
Info:
The ... you see is lua's syntax for variable arguments (these are packed into a table and used as the last argument to the function), and the unpack function takes a table and multi-returns a series of values.
If you are asking for something to call a list of functions, I just typed this very small module for you (if you can even call it that).
-- No guarantees whether this will work.
function ExecFunc (fnctn,nTimes,Threaded,...)
local to_call = function ()
fnctn(...)
end
for x = 1,nTimes do
if Threaded then
coroutine.resume(coroutine.create(to_call))
else
to_call()
end
end
end
function ExecFuncs (Async,...)
-- All parts of ... should be tables {function f, number t[, table args]}
local funcInfo = {...}
for _,funcThing in pairs(funcInfo) do
local a = funcThing.args
if a then
ExecFunc(funcThing.f,funcThing.t,Async,unpack(a))
else
ExecFunc(funcThing.f,funcThing.t,Async)
end
end
end
-- These don't check for argument validity,
-- so you should either be careful with the arguments
-- or call these in protected mode (with pcall).
If I wasted my time with that, it was fun anyway, but after typing it I reread your question... You want something to iterate through a list of functions and pass a random number to each one.
function ExecuteWithRandomValues (func_list,async)
assert(type(func_list) == "table","Expected table.")
local passbacks = {}
local threads
if async then
threads = {}
end
for _,func in pairs(func_list) do
assert(type(func) == "function","Value [" .. _ .. "] is not a function.")
local toCall = function ()
local rnd = math.random(-math.huge,math.huge)
local out = func(rnd)
passbacks[_] = {input = rnd, output = out}
end
if async then
table.insert(threads,coroutine.create(toCall))
else
toCall()
end
end
if async then
for _,thread in pairs(threads) do
coroutine.resume(thread)
end
for _,thread in pairs(threads) do
while coroutine.status(thread) ~= "dead" do
end
end
end
return passbacks
end
-- Again, no guarantees this thing is free of errors.
-- There are better ways to run and check the statuses
-- of asynchronous threads, but this is fairly convenient.

Resources