Last active
November 5, 2018 16:48
-
-
Save Phrogz/db95680ba16e93b10c31d222e5206cad to your computer and use it in GitHub Desktop.
Evaluating the same expression in multiple environments, dynamically
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
-- 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