lua-users home
lua-l archive

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


2007/9/30, Gerald Franz <gerald.franz@googlemail.com>:
> I was just wondering whether it is possible for a C extension function to to
> determine the name it was called by Lua.
> My idea would be to register a single C extension function multiple times to
> a Lua state, but behave (slightly) differently depending on the name it is
> called.
> For example, this would allow to unify all glue code between a C++ class and
> a Lua state within a single static method and facilitate a sharing of common
> code parts (e.g., converting the first argument to the pointer to the object
> instance).

In Lua a function has no name, so it cannot determine it. However it's
very easy to create new functions dynamically in Lua, so you can use
this to do what you're trying to achieve.

Suppose your C function is a global function called f, and that
receives as first parameter it's name, and subsequent parameters are
dependent on the name.

local m = {}
setmetatable(m, {__index=function(t,funcname)
    return function(...)
        return f(funcname, ...)
    end
end

Then any call to m.foo(37) will be equivalent to f("foo", 37) and
m.bar"hello" is equivalent to f("bar", "hello"). That way you can
write f once, and have different behaviour depending on the name it
was called with. Here m is a local table, but it can also be a Lua
module, a C module, or a userdata.

The above code creates a closure for each call. You can save that
closure creation with something called functables [1]. Or you can
simply cache the closures in locals:

local foo,bar = m.foo,m.bar
foo(37) -- equivalent to f("foo", 37)
bar "hello" -- equivalent to f("bar", "hello")

[1] http://lua-users.org/wiki/FuncTables