Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Created August 30, 2018 23:16
Show Gist options
  • Save cxmeel/70cdfc110fbb40aa0f16801aa4263661 to your computer and use it in GitHub Desktop.
Save cxmeel/70cdfc110fbb40aa0f16801aa4263661 to your computer and use it in GitHub Desktop.
Emulates "Constants" by locking a given table to a metatable. Also adds functions to retrieve the table's keys, values, and entries.
--[[
clockworksquirrel.const
Emulates "Constants" by locking a given table to a metatable.
Also adds functions to retrieve the table's keys, values, and entries.
Usage: <table> const(<table> table)
--]]
local t = require(script.Parent.t)
return function(Table)
assert(t.table(Table))
local Data = {
Keys = {},
Values = {},
Entries = {}
}
for Key, Value in next, Table do
Data.Keys[#Data.Keys + 1] = Key
Data.Values[#Data.Values + 1] = Value
Data.Entries[#Data.Entries + 1] = {Key, Value}
end
return setmetatable({}, {
__index = function(self, key)
if (key == '.keys') then return Data.Keys end
if (key == '.values') then return Data.Values end
if (key == '.entries') then return Data.Entries end
return Table[key]
end,
__newindex = function() error('Cannot append to locked table', 2) end,
__metatable = 'This table is locked'
})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment