Skip to content

Instantly share code, notes, and snippets.

@britzl

britzl/queue.lua Secret

Created July 10, 2017 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save britzl/001546d7e43ea85d782e894029f03e4b to your computer and use it in GitHub Desktop.
Save britzl/001546d7e43ea85d782e894029f03e4b to your computer and use it in GitHub Desktop.
Using Lua tables to represent different data structures
local q = { "first", "second", "third" }
table.remove(queue, 1) -- remove
table.insert(queue, "fourth") -- add
-- Lua table as a queue wrapped in a module (queue.lua)
local queue = {}
function queue.create(...)
local values = {...}
local instance = {}
function instance.add(element)
table.insert(values, element)
end
function instance.remove()
return table.remove(values, 1)
end
function instance.peek()
return values[1]
end
return instance
end
return queue
local queue = require "queue"
local q = queue.create("first", "second", "third")
print(q.peek()) -- first
print(q.remove()) -- first
q.add("fourth")
print(q.peek()) -- second
-- Lua table as a set
local values = { "A", "B", "C", "A", "A", "C" }
local set = {}
for _,v in ipairs(values) do set[v] = true end -- create set
if set.A then print("A is one of the values") end -- check if value exists
if not set.D then print("D is not one of the values") end -- check if value doesn't exist
-- Lua table as a multi-set
local values = { "A", "B", "C", "A", "A", "C" }
local set = {}
for _,v in ipairs(values) do set[v] = set[v] and set[v] + 1 or 1 end -- create multi-set
print("A exists " .. set.A .. " times") -- access multi-set value
-- Lua table as a dictionary
local dict = { foo = "bar", hello = "world" }
print(dict.hello) -- read value of key
if dict.foo then print("foo is a key in dict" end -- check if key-value pair exists
for k,v in pairs(dict) do print(k, v) end -- iterate key-value pairs
dict.foo = nil -- remove a key-value pair
dict.boo = "yay" -- add a key-value pair
-- Lua table as an array
local array = { 3, 5, 1, 1000 } -- create
print("Array has " .. #array .. " elements") -- length
print("First value is" .. array[1]) -- read value (1-based)
for i=1,#array do print(array[i]) end -- iterate using numeric for-loop
for i,v in ipairs(array) do print(i, v) end -- iterate using generic for-loop
table.remove(array, 3) -- remove value
table.insert(array, 2, 1234) -- insert value
-- Lua table as a queue
local q = { "first", "second", "third" }
print(q[1]) -- peek
table.remove(queue, 1) -- remove
table.insert(queue, "fourth") -- add
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment