Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Last active November 5, 2018 16:48
Show Gist options
  • Save Phrogz/db95680ba16e93b10c31d222e5206cad to your computer and use it in GitHub Desktop.
Save Phrogz/db95680ba16e93b10c31d222e5206cad to your computer and use it in GitHub Desktop.

Revisions

  1. Phrogz revised this gist Nov 5, 2018. 1 changed file with 5 additions and 3 deletions.
    8 changes: 5 additions & 3 deletions funcenv.lua
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,14 @@
    -- Set up two different environments we want our functions to be loaded under
    -- 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 a
    local expr = 'a + (b or 0)'
    -- Load the expression into a function
    local f = load('return '..expr, nil, nil, envwrap)

    -- Evaluate the expression in the context of env1
  2. Phrogz created this gist Nov 5, 2018.
    23 changes: 23 additions & 0 deletions funcenv.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    -- Set up two different environments we want our functions to be loaded under
    local env1,env2 = {a=17}, {a=1,b=25}

    -- Create a wrapper environment with a metatable
    local envmeta = {}
    local envwrap = setmetatable({},envmeta)

    -- Load a
    local expr = 'a + (b or 0)'
    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