ImmuTable
This is a Lua library that allows the creation of lightweight immutable tables.
Build
This code has been tested with Lua 5.1.5, Lua 5.2.3, Lua 5.3.5, and LuaJIT 2.0.5. To build, simply make or for LuaJIT: make LUA=luajit (you can also optionally specify LUA_INC=<path to the directory containing lua.h and lauxlib.h> or LUA_BIN=<path to the directory containing the lua binary>).
Or, with luarocks: luarocks make immutable-table-scm-1.rockspec
Usage
Here's a simple implementation of a 2-d vector using immutable tables:
1 immutable = require "immutable"
2 Vec = immutable({"x","y"}, {
5 return self.x*self.x + self.y*self.y
7 class_variable = "classvar",
8 __add=function(self, other)
9 local cls = getmetatable(self)
10 return cls(self.x+other.x, self.y+other.y)
14 assert(v.x == 2 and v.y == 3)
18 assert(t[also_v] == 'yep')
19 assert(v + Vec(0,1) == Vec(2,4))
21 assert(v:len2() == 13)
22 assert(v.class_variable == "classvar")
23 assert(tostring(v) == 'Vector(x=2, y=3)')
24 assert(Vec:is_instance(v) and not Vec:is_instance({x=2,y=3}))
25 for k, v in pairs(v) do
26 assert((k == 'x' and v == 2) or (k == 'y' and v == 3))
28 DifferentVec = immutable({"x","y"})
29 assert(DifferentVec(1,2) ~= Vec(1,2))