CSci 450/503: Programming Languages
Advanced Lua Functions

H. Conrad Cunningham

19 September 2016

Note: I corrected a few formatting errors on 29 January 2020.

Acknowledgements: These slides are adapted from the slide set 6 for the course Programming in Lua created by Fabio Mascarenhas, Federal University of Rio de Janeiro, Brazil. It was presented at Nankai University, P. R. China, in July 2013. Although that course used Lua 5.2, I have attempted to update these slides to Lua 5.3.

Advisory: The HTML version of this document may require use of a browser that supports the display of MathML. A good choice as of September 2016 is a recent version of Firefox from Mozilla.

ADVANCED LUA FUNCTIONS

Iterating over ...

Function table.unpack

“Named” Arguments

Lexical Scoping

Closures (1)

Closures (2)

    function counter() 
       local n = 0 
       return function () 
                n = n + 1  -- n non-local to returned function
                return n 
              end 
    end

Closures and Sharing

Callbacks

Functional Programming

Lua map Function

Lua filter Function

Lua Fold Functions (1)

Lua Fold Functions (2)

Curried Functions (1)

Curried Functions (2)

    function map2(f)
        return function(l) 
                 local nl = {} 
                 for i, x in ipairs(l) do 
                   nl[i] = f(x) 
                 end
                 return nl
               end
    end 

Quiz

What is wrong with the function named below, that turns a function f with positional arguments into a function with named arguments? How to fix it?

    function named(f, names)    -- names: names to position
        return function (args)  -- args: names to values
                 local l =
                   map(function (name) return args[name] end, names) 
                 f(table.unpack(l)) 
               end 
    end 

    rename = named(os.rename, { "old", "new" }) 
    rename{ old = "old.txt", new = "new.txt" }

Quiz Solution

    function named(f, names)    -- names: name to position
        return function (args)  -- args: names to values
                 local l = 
                   map(function (name) return args[name] end, names) 
                 f(table.unpack(l)) 
                 -- return f(table.unpack(l,1,#names)) 
               end 
    end 

    rename = named(os.rename, { "old", "new" }) 
    rename{ old = "old.txt", new = "new.txt" }