lua-users home
lua-l archive

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


2017-06-01 17:33 GMT+02:00 Francisco Olarte <folarte@peoplecall.com>:
> On Thu, Jun 1, 2017 at 11:24 PM, Martin <eden_martin_fuhrspam@gmx.de> wrote:
>> On 05/31/2017 06:11 PM, Andrew Starks wrote:
> ...
>>> An upvalue is a local that has been declared in a parent scope and not
>>> covered over by a local declaration:
>
>> Function parameters are upvalues too. This looked quite strange to me.
>> local f =
>>   function(a)
>>     return
>>       function()
>>         a = a + 1
>>         return a
>>       end
>>   end
>> local counter = f(0)
>> print(counter(), counter())
>
> Doesn't look weird to me. a is local to f, the outer function, (
> parameters act like automagically initialized locals in many languages
> ) , so it is an unconvered local in the parent scope ( which is the
> outer function body ) of the inner function.
>

Change the name 'f' to 'newcounter', then it will look less weird
The example demonstrates a standard idiom, e.g.

function basket(tbl)
  return function(...)
    tbl[#tbl+1] = {...}
  end
end

words={}
string.gsub("the quick brown fox jumps over the lazy
dog","()(%S+)",basket(words))
for k,v in pairs(words) do print(table.unpack(v)) end