kyleconroy / lua-state-machine

A finite state machine lua micro framework
MIT License
354 stars 66 forks source link

Tail calls gives "stack overflow" #13

Closed Arkoniak closed 10 years ago

Arkoniak commented 10 years ago

According to http://www.lua.org/pil/6.3.html lua supports tail calls, and the following example really gives infinite loop

function room1()
    print("Room1")
    return room2()
end

function room2()
    print("Room2")
    return room3()
end

function room3()
    print("Room3")
    return room1()
end

room1()

Yet, direct implementation of this code using lua-state-machine yields stack overflow

local machine = require 'statemachine'

local fsm = machine.create({
    initial = 'room1',

    events = {
        { name = 'go', from = 'room1', to = 'room2' },
        { name = 'go', from = 'room2', to = 'room3' },
        { name = 'go', from = 'room3', to = 'room1' },
    },
    callbacks = {
        onroom1 = function(self, event, from, to) print("Room1"); return self:go() end,
        onroom2 = function(self, event, from, to) print("Room2"); return self:go() end,
        onroom3 = function(self, event, from, to) print("Room3"); return self:go() end,
    }
})

fsm:go()

Well, may be I am not using it properly...

kyleconroy commented 10 years ago

You're using the library correctly, but tail recursion is not support by lua-state-machine. The reason I don't support tail recursion is due to the calling location for callbacks. The 'onroomN' callbacks are called in this location, which is not an actual return statement.

As support for tail recursion would require a signification rewrite, I won't be able to fix this problem. Sorry!