lua-users home
lua-l archive

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



> Yeah, one of the coolest features of Lua is using stuff as keys, indices, etc. :) I thought since the function name was already hanging around I would just use that unless there is a performance gain to be had by using the function as an index. If I did it that way, would Lua consider the function as an index in the same way as say light user data? Or is there a special relationship that functions have as indices?

The function name is not "hanging around". The function doesn't actually have a name. In order to deduce what you think the name of the function might be, Lua searches through the stack and the global variables looking for something whose value is the function. This is not particularly efficient, although it is nice for debugging.

Consider this code:

function foo(x) print("The value is "..tostring(x)) end

bar = foo

Now, what is the name of that function? (If you use the debugging package, either "foo" or "bar" might come up.)

> Also, how would I get the funciton name in the beginning to use it as an index? The reason I hadn't just made keys of the functions is that at load time the function is embedded in a chunk and I don't have a real good way of knowing the function is even there until it gets passed in as a paramter.

There is some code in the lazy tables tutorial on the wiki, which is intended to help with this problem. It attaches a metatable to the global environment which traps "assignments" (with __newindex) and reverse indexes the value with the "name" into a weak-keyed table; this works for functions, tables, threads and userdata. You might find that useful as a model. It is also a heuristic, though -- if you redefine a global, it will not pick that up, whereas the debug package might.

That said, I don't understand how you can be attaching data to a function without knowing that the function exists. If you are attaching the data after you find out that the function exists, then you already have the function and can use that as an index.

HTH,
Rici