Created
March 28, 2018 06:42
-
-
Save vurdalakov/62ef57ef40ed01dd69a8cd9e61b16406 to your computer and use it in GitHub Desktop.
[Lua] Remove (and return) a table element by its key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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