Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Created March 28, 2018 06:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vurdalakov/62ef57ef40ed01dd69a8cd9e61b16406 to your computer and use it in GitHub Desktop.
Save vurdalakov/62ef57ef40ed01dd69a8cd9e61b16406 to your computer and use it in GitHub Desktop.
[Lua] Remove (and return) a table element by its key
-- Removes (and returns) a table element by its key, moving down other elements to close space and decrementing the size of the array
function table.removeKey(table, key)
local element = table[key]
table[key] = nil
return element
end
-- Test
printf = function(s, ...) return io.write(s:format(...)) end
function table.print(table)
for key, value in pairs(table) do
printf('(%s)=(%s)\n', tostring(key), tostring(value))
end
end
local prefs = {['key1'] = 'value1', ['key2'] = 'value2'}
table.print(prefs)
print('---')
local removedElement = table.removeKey(prefs, 'key1')
table.print(prefs)
print('---')
print(removedElement)
--[[ Result:
(key1)=(value1)
(key2)=(value2)
---
(key2)=(value2)
---
value1
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment