Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

local variables in Perl and Lua

Name: Anonymous 2011-07-22 21:32

I didnt get an answer for this in the Python thread, so I'll ask here: Why do variables have to have the local keyword to make their scope local? Why cant it just use implicit lexical scope like most any other languages?

Name: Anonymous 2011-07-22 22:11

>>4
its a dynamic language so it could be either
there you go

local x = 1 -- new x, always
x = 1 -- rebinding to existing x
technically the second one might create a new global if there aren't visible x locals, although there's only one global scope anyway so it doesn't really matter. it could go a step further and require declaring globals as well but that isn't going to happen for a while

also, in lua 5.2 the following code relies on being able to create new locals on demand

local environment = {
    a = { x = 10 },
    b = { x = 20 },
    c = { x = 30 },
}
do
    local _G = _G
    local _ENV = environment.a
    function printx () _G.print(x) end

    local _ENV = environment.b
    function printx () _G.print(x) end

    local _ENV = environment.c
    function printx () _G.print(x) end
end
environment.a.printx()
environment.b.printx()
environment.c.printx()

this probably isn't the greatest example because if people used _ENV like this in real-world code they'd probably be flayed

sure you could put those into their own functions but working around crappy scoping rules via closures is a javascript thing

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List