lua-users home
lua-l archive

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


2016-08-01 3:29 GMT+02:00 Soni L. <fakedme@gmail.com>:
> If I have this:
>
> local t = {}
> local another_function(wrapped, ...)
>   print(t[wrapper])
> end
> local function wrap(something_important)
>   local function wrapper(...)
>     return another_function(wrapper, ...)
>   end
>   t[wrapper] = something_important
>   return wrapper
> end
>
> Is it guaranteed that 2 calls to wrap() won't cause weird fucked-up
> semantics? E.g. can I do this?
>
> local wrap1 = wrap(1)
> local wrap2 = wrap(2)
> wrap1() --> prints 1
> wrap2() --> prints 2

There are three sections of the manual that must be read together in
order to answer this question. Here they are. How about reading them
carefully and if you still think the issue is unclear, putting your finger
the spot where doubt remains?

3.4.4 ... Closures with the same reference are always equal. Closures
with any detectable difference (different behavior, different
definition) are always different.

3.4.11 ... A function definition is an executable expression, whose
value has type function. When Lua precompiles a chunk, all its
function bodies are precompiled too. Then, whenever Lua executes the
function definition, the function is instantiated (or closed). This
function instance (or closure) is the final value of the expression.

3.6 ... Consider the following example:

     a = {}
     local x = 20
     for i=1,10 do
       local y = 0
       a[i] = function () y=y+1; return x+y end
     end

The loop creates ten closures (that is, ten instances of the anonymous
function). Each of these closures uses a different y variable, while
all of them share the same x.