Skip to content

Instantly share code, notes, and snippets.

@arkenidar
Created May 5, 2025 19:51
Show Gist options
  • Save arkenidar/40325d2353e68ddd0e49039a9a8c4a7c to your computer and use it in GitHub Desktop.
Save arkenidar/40325d2353e68ddd0e49039a9a8c4a7c to your computer and use it in GitHub Desktop.
lang-tech : language techniques

set

Python set

# Using curly braces
my_set = {1, 2, 3, 4}
my_set.add(5)
my_set.remove(3)

print(1 in my_set)  # Output: True
print(6 in my_set)  # Output: False

for element in my_set:
    print(element)

Lua set

https://www.lua.org/pil/11.5.html

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

reserved = Set{"while", "end", "function", "local", }

set-impl.lua

-- file : set-impl.lua

function SetBelongs(myset, item)
  return myset[item] and true or false
end

function SetAdd(myset, item)
  myset[item] = true
  return myset
end

function SetDel(myset, item)
  myset[item] = nil
  return myset
end

function SetNew(list)
  local set = {}
  for _, value in ipairs(list) do
    set[value] = true
  end
  return set
end

function SetList(myset)
  for key, value in pairs(myset) do
    print(key)
  end
end

set-use.lua

-- file : set-use.lua

require("set-impl")

local function TestSetFunctions()
  print("# initial set :")
  local myset = SetNew{ 1, 2, 3, 4, }
  SetList(myset)

  print("# add 5 to set :")
  myset = SetAdd(myset, 5)
  SetList(myset)

  print("# remove 3 from set :")
  myset = SetDel(myset, 3)
  SetList(myset)

  print("# belongs to set or not :")
  print(SetBelongs(myset, 1) and "1 belongs" or "1 does not belong")
  print(SetBelongs(myset, 6) and "6 belongs" or "6 does not belong")
end

TestSetFunctions()

output ( running set-use.lua )

# initial set :
1
2
3
4
# add 5 to set :
1
2
3
4
5
# remove 3 from set :
1
2
4
5
# belongs to set or not :
1 belongs
6 does not belong
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment