lua-users home
lua-l archive

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


On Sep 22, 2013, at 3:41 PM, Doug Currie wrote:

> You are correctly describing the implementation of Lua values, perhaps not the simplest semantics for some people. There is an equivalent way to look at this: the semantics for all values is by reference; some values are mutable (tables, userdata), most values are not mutable (numbers, strings, booleans).

Functions are an interesting case. Let's write:

function make_counter()
    -- commented out: local i=0
    return function() i=i+1; return i end
end

f = make_counter()

So is what's in f mutable? How could you tell?

If we add "local i = 0" to the top of make_counter, we have the stereotypical closure. In that case we can reason about the minimum time the return value of make_counter() must be alive in order to be distinct from other return values.

In general, questions about object lifespan can be converted to questions about whether an infinite loop exhausts storage in a finite time. That's the upshot of opaque phrases like "must be properly tail-recursive." You're guaranteed this will not run out of memory:

local g
g = function() 
  print("y") 
  return g();
end
g()

Similarly, you can concoct infinite loops which test garbage collection. Instead of that print() call, we could have:

  x = "a"

or 

  x = {}

or

  x[#x + 1] = 7
  x[#x - 1] = nil
  print(#x)

Well, that last one is dependent on x (and spooky hidden variables), but storage used will not grow without bounds. Right?

Jay