lua-users home
lua-l archive

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


> 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