lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hey everybody, I just released a library that allows you to create immutable tables in Lua. The tables are stored compactly and instances are interned (but garbage collected), so the immutable tables can be used as table keys. I know there's been a lot of talk lately about "arrays with holes", and my library supports that. Here's an example of some of the functionality of the library:

Immutable = require("immutable")
Tuple = Immutable()
local foo = Tuple(1,nil,3,nil)
assert(#foo == 4)
assert(foo[1] == 1 and foo[2] == nil and foo[3] == 3 and foo[4] == nil)
local t = {[foo]="works as key"}
assert(t[Tuple(1,nil,3,nil)] == "works as key")
Point = Immutable({"x", "y"}, {name="Point", __add = function(a,b) return Point(a.x+b.x, a.y+b.y) end})
local p1 = Point(2,3)
assert(p1.x == 2 and p1.y == 3)
local p2 = p1 + Point(3,4)
assert(p2 == Point(5,7))
assert(tostring(p2) == "Point(x=5, y=7)")

Right now, the library is written for compatibility with the Lua 5.1/Lua 5.2/Lua 5.3/LuaJIT 2.0 APIs, so it's not making use of the userdata-can-have-multiple-values feature from Lua 5.4 (which I'm looking forward to because it will make the library even more efficient). Nonetheless, the library is decently efficient and I've been using and testing it in a project for a couple months now, so it should be pretty stable. I've really enjoyed using my library so far, and I hope you all like it too. Let me know if you find any bugs or find the library useful.

Source repo (with API and implementation documentation): https://bitbucket.org/spilt/lua-immutable/src
LuaRock: http://luarocks.org/modules/spill/immutable-table
or install directly via: luarocks install --server=http://luarocks.org/dev immutable-table

--
Bruce

Attachment: signature.asc
Description: Message signed with OpenPGP