lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 23 June 2011 22:46, David Given <dg@cowlark.com> wrote:
> local function statemachine()
>        local i = 1
>        local j = 2
>
>        local state1
>        local state2
>
>        state1 = function() i = i + 1 return state2() end
>        state2 = function() j = j + 1 end
>
>        return state1()
> end
>
> ...allocates at least four heap cells *every time* statemachine() is
> called; don't forget, the state functions themselves are upvalues...
>
> The only other option is to pass your shared data in and out of every
> state. But that's incredibly messy and hard to write and it's *still*
> slower than an honest goto.


how is it messy/hard?

--[[
local done = function(...) return ... end
local state1,state2

state1 = function(i,...)
    i=i+1
    return state2(i,...)
end
state2 = function(i,j,...)
   j = j + 1
   return done(i,j,...)
end

print(state1(1,2))
]]

Sure you have to manage your parameter lists; but its not too bad; you
only have to copy+paste; and you only need to do up to what you need
(cause you just follow it with a vararg)
the alternative is to use a table call:

--[[
local s = {}
function s:state1()
    self.i=self.i+1
    return self:state2()
end
function s:state2()
   self.j = self.j + 1
   return self
end

local statemachine = setmetatable({},{__index=s})
local res = statemachine:state1{i=1,j=2}
print(res.i,res.j)
]]

You do have to use 'self' a bit; and it might not be as fast
(benchmarks anyone; include luajit...) but its adequate.

Daurn.