How to use upvalues in Lua

Posted by Nick Gammon on Wed 07 Jun 2006 09:52 PM — 1 posts, 7,850 views.

Australia Forum Administrator #0
It has taken a while for me to get my brain around what Lua "upvalues" are, and where they could be useful.

Let's start with a small example, we want a function that will count something every time it is called. The question is, where do we keep the counter?

One approach is to make a global variable:


count = 0

function counter ()
  count = count + 1
  print ("count now ", count)
end -- counter

counter () --> count now 1
counter () --> count now 2


However an obvious problem here is that we only have a single counter "count" and it is shared with other global variables. Maybe another function will change it, and we can only count one thing at a time.

We can try making the count a local variable, where other functions cannot touch it, but that doesn't work too well:


function counter ()
  local count = 0
  count = count + 1
  print ("count now ", count)
end -- counter

counter () --> count now 1
counter () --> count now 1


Clearly the count will always be 1 in this case.

We need a place to store the count which is neither a global variable or a local variable. This is where upvalues are useful.


function make_counter (name)
  local count = 0
  return function ()
    count = count + 1
    print (name, "now", count)
  end -- local function
end -- counter

counter = make_counter ("fish")
another_counter = make_counter ("chips")

counter ()  --> fish now 1
counter ()  --> fish now 2
another_counter ()  --> chips now 1
counter ()  --> fish now 3



In this example we can have two counters simultaneously, both independently incrementing. This example also stores the name of the counter as an upvalue. Thus each counter we instantiate (with make_counter) has two upvalues: the name of the counter, and the current counter value.

We can write a small function to show us the upvalues for a particular function:


function showupvalues (f)
  assert (type (f) == "function")
  
  local i = 1
  local name, val
  
  repeat
    name, val = debug.getupvalue (f, i)
    if name then
      print ("index", i, name, "=", val)
      i = i + 1
    end -- if
  until not name

end -- function showupvalues



Now applying this to counter (after the above test) we see:


index 1 count = 3
index 2 name = fish


In summary, to use upvalues we need a "wrapper" function. When the wrapper function returns a function to the caller, it converts any local variables (local to the wrapper) into upvalues. Arguments to the wrapper function are considered to be local variables.



Function to find something in a numerically-indexed table

To demonstrate a more elaborate use for this, let's consider the case of where we need to scan through a table looking for a particular value (not a key).

Here is an example, written without using upvalues:


t = { "all", "good", "boys", "deserve", "fruit" }

i = table.foreachi (t, 
      function (k, v)
        if v == "boys" then
          return k
        end -- if
      end -- function
      )
  
print (i)  --> 3


The problem here is that the word I am searching for ("boys") either has to be a literal, or an external variable. Hoever we can write a wrapper function that returns the comparison function and remembers what we are searching for:


-- helper function for use with table.foreachi
-- returns a function with "what" as an upvalue
function finder (what)
  return function (k, v)
    if v == what then
      return k
    end -- if found
  end -- function 
end -- finder

t = { "all", "good", "boys", "deserve", "fruit" }

print (table.foreachi (t, finder ("boys")))  --> 3
print (table.foreachi (t, finder ("good")))  --> 2


Now the "finder" function returns a function which can be used with table.foreachi, with that function remembering in an upvalue what it is we are searching for.