Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Last active November 5, 2018 16:48
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 Phrogz/db95680ba16e93b10c31d222e5206cad to your computer and use it in GitHub Desktop.
Save Phrogz/db95680ba16e93b10c31d222e5206cad to your computer and use it in GitHub Desktop.
Evaluating the same expression in multiple environments, dynamically
-- An expression to evaluate
local expr = 'a + (b or 0)'
-- Set up two different environments we want our expression to be evaluated against
local env1,env2 = {a=17}, {a=1,b=25}
-- Create a wrapper environment with a metatable
local envmeta = {}
local envwrap = setmetatable({},envmeta)
-- Load the expression into a function
local f = load('return '..expr, nil, nil, envwrap)
-- Evaluate the expression in the context of env1
envmeta.__index = env1
print(f()) --> 17
-- Evaluate the expression in the context of env2
envmeta.__index = env2
print(f()) --> 26
-- You can even combine environments, with env1 shadowing env2
envmeta.__index = env1
setmetatable(env1,{__index=env2})
print(f()) --> 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment