Skip to content

Instantly share code, notes, and snippets.

@lukego
Created November 13, 2012 12:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukego/4065602 to your computer and use it in GitHub Desktop.
Save lukego/4065602 to your computer and use it in GitHub Desktop.
Object oriented programming in Lua

Simple example of object-oriented programming in Lua. Objects are represented as tables so they are easy to invoke methods on, but their state is kept in a closure where it's convenient for methods to access.

Example of a simple stateful "counter" object with two methods:

module("counter", package.seeall)

function new (count)
   local M = {}

   -- Method: increase the counter value
   function M.add (n)
     count = count + (n or 1)
   end

   -- Method: Return the current counter value
   function M.value ()
     return count
   end

   return M
end

Here's an example usage, creating two counters with different values:

counter = require("counter")
local a, b = counter.new(1), counter.new(2)
a.add(); b.add()
print(a.value(), b.value())
==> 2       3

Looks good to me. But I have questions!

  • Is this idiomatic Lua? (Pointer to other code doing the same thing?)
  • Is there a better way? (Please show!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment