lua-users home
lua-l archive

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

Gavin Kistner a écrit :
That's the internal model I'm seeing. Closures do not bind to values,
but rather to variables that hold or reference values. Each usage of
'local' creates a new variable.

"a = 30" has to figure out what 'a' is, and finds the recently-declared
'a' which the 'g' closure is also using. Modifying the value in the
variable affects the closure as well.

"local a = 30" doesn't look to see if another existing local 'a' exists;
it just creates a brand new variable. This behavior only surprises me
because it is different from how JavaScript's "var" keyword behaves.

Does this mean that:

local t = ''
	local r = math.random(1, 50)
	t = t .. " " .. r
until (string.len(t) > 100)

is less efficient than declaring the local r outside the loop?
At least in terms of memory?

This idiom is very frequent in (semi-)compiled languages (C++/Java...), relying on the compiler optimizations to put the variable declaration outside the loop, but it can be an overkill in Lua. Being old-fashioned and from a time where compilers weren't so good, I tends to put the declarations outside loops if I can...

Since there is no function declaration here, I suppose there is no closure, so I am unsure if your statements are still true here.

Philippe Lhoste
--  (near) Paris -- France
--  --  --  --  --  --  --  --  --  --  --  --  --  --