# Recursive functions in Lua 4

5 messages
Open this post in threaded view
|

## Recursive functions in Lua 4

 Hi. I have to maintain some Lua 4 code, and I have no idea how to make a local function call itself. In the following code, I'd like to make G local to the function F. Is this possible? function F()     G = function(value)         if value == 10 then             return "stop"         end         return G(value + 1)     end         print( G(1) ) end print( F(1) ) assert(not G, "G escaped to the global scope")
Open this post in threaded view
|

## Re: Recursive functions in Lua 4

 On Thu, 21 May 2009 13:00:56 -0300 Ignacio Burgueño <[hidden email]> wrote: > Hi. I have to maintain some Lua 4 code, and I have no idea how to > make a local function call itself. > In the following code, I'd like to make G local to the function F. Is > this possible? > > function F() > >     G = function(value) >         if value == 10 then >             return "stop" >         end >         return G(value + 1) >     end >     >     print( G(1) ) > end Yes.  Declare the local variable before assigning to it; function F()         local G         G = function(value)                 if value == 10 then                         return "stop"                 end                 return G(value + 1)         end         print( G(1)) end B.
Open this post in threaded view
|

## Re: Recursive functions in Lua 4

 In reply to this post by Ignacio Burgueño > Hi. I have to maintain some Lua 4 code, and I have no idea how to make a   > local function call itself. > In the following code, I'd like to make G local to the function F. Is   > this possible? > > function F() > >    G = function(value) >        if value == 10 then >            return "stop" >        end >        return G(value + 1) >    end >      print( G(1) ) > end > > print( F(1) ) > assert(not G, "G escaped to the global scope") Lua 4 does not have lexical scope, so you should use upvalues. But you cannot use an upvalue before giving it its final value. One way out of this is to use a table to create an indirection:   function F ()     local t = {}     t.G = function (value)             if value == 10 then               return "stop"             end             return %t.G(value + 1)           end     print( t.G(1) )   end Not pretty, but I cannot think of anything better. -- Roberto