Skip to content

Instantly share code, notes, and snippets.

@mirven
Created December 8, 2009 23:56
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 mirven/252114 to your computer and use it in GitHub Desktop.
Save mirven/252114 to your computer and use it in GitHub Desktop.
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