Lua Exercises

Author: Luc V. Talatinian

CPS 499-03: Emerging Languages, Spring 2017

  1. (Tables) Define a time class in Lua using a metatable and object prototype function.
    • A time object stores a 24-hour time value (this could be done several ways).
    • Define a prototype function in your metatable called new() that returns a new instance of a time object (initially at 00:00:00).
    • Provide the following interface:
      • tick(): adds one second to the timer.
      • reset(): reset the time to 00:00:00.
      • set(t): sets the value to the new time immediately (input can be either a string of the form hh:mm:ss or an integer representing the number of seconds since 00:00:00).
      • format(): returns a string of the current time value formatted in the style hh:mm:ss.
    • Provide the following functionality for each time object through the metatable:
      • Addition, subtraction between times (must account for overflow)
      • Comparison
      • Indexing: t[1] gives the hours, t[2] the minutes, and t[3] the seconds (may not require a metamethod depending on your implementation)

  2. (Coroutines) Create a function spawn_fact_chain(n) that sequentially spawns a variable number of coroutines (specified by n) that print (in order) the result of factorial(1) to factorial(n), in the order that each coroutine is created. Your implementation must avoid recomputation of the factorial across coroutines (i.e. you should only perform one multiplication per coroutine, minus the first).

  3. (Program extension) Familiarize yourself with the Lua interface to vim (here). Create a Lua script that when run in vim will insert a new C-style comment-block (see format below) time-stamped. See the example below for formatting of the comment block. Use of your solution from problem 1 with some minor changes to the prototype and format() functions is recommended, but not required.
    • When complete, you should be able to run the command :luafile [your script file] for the desired effect.
    • Note that you must be using vim for Lua support; the original vi editor did not include Lua functionality.
    • Example transformation:
    • #include <iostream>
      using namespace std;
      
      int main(int argc, char** argv)
      {
          printf("supplied argument count is %d", argc);
      }
      
      // after running ':luafile [script]' w/ cursor on line 5:
      
      #include <iostream>
      using namespace std;
      
      int main(int argc, char** argv)
      {
          /* 22 Mar 2017 [13:57:00]
           */
          printf("supplied argument count is %d", argc);
      }