lua-users home
lua-l archive

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


On 7/29/08, King, Mike <MKing@klmicrowave.com> wrote:
> Has anyone created Set operators for tables in Lua?

I made the attached very noddy set implementation once.

Works for me:

Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> dofile "sets.lua"
> S1 = Set:new()
> S2 = Set:new()
> S1:add(1)
> S1:add(42.42)
> S1:add("foobar")
> S1:add({ 1, "bla" })
> S2:add(1)
> S2:add("foobar")
> =S1:elem(42.42)
true
> =S1:elem({ 1, "bla" })
true
> =S1:size()
4
> =S2:size()
2
> U=S1:union(S2)
> =S1:size()
4
> =S2:size()
2
> =U:size()
4
> =U:elem({ 1, "bla" })
true
> D=S1:diff(S2)
> =D:size()
2
> for _, v in pairs(S1) do print(v) end
table: 0033E9D0
42.42
1
foobar
> for _, v in pairs(S2) do print(v) end
1
foobar
> for _, v in pairs(U) do print(v) end
foobar
42.42
1
table: 0033E9D0
> for _, v in pairs(D) do print(v) end
42.42
table: 0033E9D0
>


Robby

Attachment: sets.lua
Description: Binary data