Skip to content

Instantly share code, notes, and snippets.

@juntalis
Last active August 27, 2017 08:22
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 juntalis/5767003ff7aebed721d07758d00447f4 to your computer and use it in GitHub Desktop.
Save juntalis/5767003ff7aebed721d07758d00447f4 to your computer and use it in GitHub Desktop.
Bypass redis script sandboxing in order to force a set of variables into the global namespace. Use Case: Having a heavily-used script with a bunch initialization time processing (class building, constants tables, etc) that will always execute the exact same way regardless of the user input from ARGV and KEYS or the state of redis's data. This sc…
local function force_globals(globs)
-- Check for metatable on _G. If no metatable exists,
-- create one.
local _G_mt = getmetatable(_G)
if _G_mt == nil then
return setmetatable(_G, {
__index=globs
})
end
-- Metatable exists. Check for existence of __index
-- and either set or merge our globals into it.
local _G_index = _G_mt.__index
if _G_index == nil then
_G.__index = globs
else
for key, value in pairs(globs) do
_G_index[key] = value
end
end
return _G
end
local function expensive(value)
return value + 1
end
local MY_GLOBALS = {
CONSTANT_CASE_A=expensive(0),
CONSTANT_CASE_B=expensive(1),
CONSTANT_CASE_C=expensive(2),
CONSTANT_CASE_D=expensive(3),
CONSTANT_CASE_E=expensive(4),
CONSTANT_CASE_F=expensive(5),
}
force_globals(MY_GLOBALS)
return { CONSTANT_CASE_A, CONSTANT_CASE_B, CONSTANT_CASE_C }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment