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!)