lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Saturday 12 June 2004 13:14, Dan East wrote:
>   I've read many posts in the archive about determining function names, but
> I don't know if that is even necessary in this case.
>   A LUA script passes a LUA function as a parameter to my C function. 
> Later I need to push that LUA function back on the stack (or more
> specifically just a reference to the function).  It seems like this should
> be a very simple task.  Must I determine the name of the function in this
> case?  One caveat is that the function will be redefined between the time
> it is passed to my C function and when it is pushed back on the stack by
> another C function.

Ok, your first problem is that it does not make sense to talk about a function 
being redefined. A function just is. It doesn't have a name, and it can't be 
changed once created (except for values held by closures). You can create a 
different function and assign it to the same variable, but that's like 
assigning 5 to a variable instead of 3: the number isn't somehow changed, 
just the value held by that particular variable.

So, what you're really asking for is call by reference. Lua doesn't support 
this per se, but you can get the effect using tables:

-- Create a table to use as a reference,
-- and set its initial value to my_function
ref = { my_function }

-- Pass the table to your C function
-- The C function should save the table in the registry or something
my_c_function(ref)

-- Note that changing the value of the my_function variable here will
-- not affect the value stored in the table.

-- Change the reference
ref[1] = my_other_function

-- Note that ref = { my_other_function } would NOT work, because that
-- would create a different table.

-- Call the C function that's going to recover the table from the registry.
my_other_c_function()

-- Jamie Webb