Why use local variables?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
vrld
Party member
Posts: 917
Joined: Sun Apr 04, 2010 9:14 pm
Location: Germany
Contact:

Re: Why use local variables?

Post by vrld » Fri Aug 30, 2013 8:39 am

Not sure why no-one mentioned this yet, but local variables are the only way to create closures. A toy example:

Code: Select all

messages = {'hey!', 'listen!'}
closures = {}
for i = 1,10 do
    local m = messages[math.random(#messages)]
    closures[i] = function() print(m) end
end

for _, f in ipairs(closures) do
    f()
end
Or this

Code: Select all

function newCounter()
    local i = 0
    return function(inc)
        i = i + (inc or 1)
        return i
    end
end

a, b = newCounter()
print(a(3)) --> 3
print(a(), b()) --> 4, 1
I have come here to chew bubblegum and kick ass... and I'm all out of bubblegum.

hump | HC | SUIT | moonshine

User avatar
seeker14491
Prole
Posts: 9
Joined: Thu Nov 29, 2012 10:47 pm

Re: Why use local variables?

Post by seeker14491 » Sat Nov 02, 2013 8:58 am

vrld wrote:

Code: Select all

function newCounter()
    local i = 0
    return function(inc)
        i = i + (inc or 1)
        return i
    end
end

a, b = newCounter()
print(a(3)) --> 3
print(a(), b()) --> 4, 1
b is nil, so that last line would error.

User avatar
Roland_Yonaba
Inner party member
Posts: 1562
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Why use local variables?

Post by Roland_Yonaba » Sat Nov 02, 2013 10:41 am

seeker14491 wrote:b is nil, so that last line would error.
True. I guess what vrld wanted to mean was:

Code: Select all

    -- same as before ...
    a, b = newCounter(), newCounter()
    -- same as before ...

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 5 guests