Created
December 8, 2009 23:56
-
-
Save mirven/252114 to your computer and use it in GitHub Desktop.
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
local stored_functions = {} | |
function create_function(arg_names, body) | |
return function(...) | |
local args = {...} | |
local env = setmetatable({}, { __index = getfenv() }) | |
for index, an in ipairs(arg_names) do | |
env[an] = args[index] | |
end | |
local func = stored_functions[body] or loadstring(body) | |
stored_functions[body] = func | |
setfenv(func, env) | |
return func() | |
end | |
end | |
print(create_function({"i"}, "return i+2")(5)) -- "|i| return i+2" | |
print(create_function({"i", "j"}, "return i+j")(5,10)) -- "|i,j| return i+j" | |
print(create_function({"i", "j", "k"}, "return i+j+k")(5,10,11)) -- "|i,j,k| return i+j+k" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment