Posted by
| Nick Gammon
Australia (23,133 posts) Bio
Forum Administrator |
Message
| Yes I was thinking along those lines, but you don't need to use local variables inside the function because arguments are automatically upvalues. Try this:
function makefunc (name, f)
_G [name] =
function (...)
f (name, unpack (arg))
end -- local function
end -- makefunc
This function does everything in one hit, adds the function "f" into the global namespace with name "name", and remembers the name as an upvalue, so when "f" is called it is supplied an initial argument, which is the name it was called. Examples:
function test (name, a, b, c)
print ("in test:", name, a, b, c)
end -- test
function test2 (name, ...)
print ("in test2:", name, unpack (arg))
end -- test2
makefunc ("Nick", test)
makefunc ("Tsunami", test)
makefunc ("Ked", test2)
Nick ("foo", "bar", "look") --> in test: Nick foo bar look
Tsunami ("x", "y", "z") --> in test: Tsunami x y z
Ked ("ready", "set", "go", "let's", "move", 42) --> in test2: Ked ready set go let's move 42
You can see from this that the newly created functions, Nick, Tsunami and Ked, all remembered both their own names, and the functions they should call.
The called functions can also be passed arguments. By using "..." and "unpack (arg)" we can pass any number of arguments to the final function.
We can check they are upvalues by using the "showupvalues" function I wrote for another thread:
function showupvalues (f)
assert (type (f) == "function")
local i = 1
local name, val
repeat
name, val = debug.getupvalue (f, i)
if name then
print ("index", i, name, "=", val)
i = i + 1
end -- if
until not name
end -- function showupvalues
print (test) --> function: 00325590
showupvalues (Nick)
--> index 1 f = function: 00325590
--> index 2 name = Nick
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | Top |
|