[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Trying to resolve name of a function inside an argument list
- From: "Peter Cawley" <lua@...>
- Date: Mon, 8 Oct 2007 14:43:29 +0100
You can also make use of metatables to register the names of functions:
##
function autofunc_table(t, name)
if (not function_name[t]) -- prevent recursion
or (string.len(name) < string.len(function_name[t])) then -- use the
shortest alias
function_name:add(t,name)
-- handle existing entries
for k,v in pairs(t) do
if type(v) == "table" then
autofunc_table(v, name .. k .. ".")
elseif type(v) == "function" then
function_name:add(v,name .. k)
end
end
-- handle future entries
local mt = getmetatable(t) or {}
mt.__newindex = autofunc_table_newindex
setmetatable(t, mt)
end
end
function autofunc_table_newindex(t,k,v)
local name = function_name[t]
rawset(t,k,v)
if type(v) == "table" then
return autofunc_table(v, name .. k .. ".")
elseif type(v) == "function" then
function_name:add(v,name .. k)
end
end
function_name = setmetatable({}, {__mode = "k"}) -- weak keys in lookup table
function_name.add = function(t,k,v)
if t[k] == nil or string.len(v) < string.len(t[k]) -- use the shortest alias
t[k] = v
end
end
autofunc_table(_G, "")
##
After putting that into a source file, then the following is possible:
##
function lua_c_func(f)
print(function_name[f])
end
lua_c_func(ipairs)
lua_c_func(math.sin)
ipairs = nil
lua_c_func(ipairs)
str = string
lua_c_func(string.len)
lua_c_func(package.loaded.math.cos)
##
The output of which is:
##
ipairs
math.sin
nil
str.len
math.cos
##
On 08/10/2007, W. C. Bubel <inmatarian@gmail.com> wrote:
> Lua's Tables can use any type, except nil, as both key and value. If you
> want a way to get a function's name, you can build your own lookup table
> matching functions to names. That is to say, in addition to saying this:
> my_table["my_func"] = my_func
> You could also say this:
> my_table[my_func] = "my_func"
>
> That way, when faced with a function whose name you don't know,
> my_table[unknown_func] should yield it's name. This only works with
> functions you've written yourself and explicitly added to the lookup table.
> You could probably write something to ease that for you...
>
> function my_table:addfunc( func_name, func_body )
> self[func_body] = func_name
> end
>
> The result would be my_table:addfunc( "foo", function print("bar") end )
>