lua-users home
lua-l archive

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


It was thus said that the Great jseb once stated:
> >   Take a look at package.loaded.  Not only does it contain a
> > reference to package, but it also contains a reference to _G.
> 
> Ah yes, just saw that.
> 
> And there were problem also in the searching loop: when found, the
> search continues and it ends with returning nil. Each returning
> call should test if there were some success previously.
> 
> Correct version:
> 
> function _get_fx_name(fx, t)
>   local ret = nil
>   for k,v in pairs(t) do
>     if fx == v then
>       print("found", k,v)
>       return k
>     end
>     if type(v) == "table" and k ~= "_G"  and k ~= "package" then
>       ret = _get_fx_name(fx, v)
>       if ret then goto exit end
>     end
>   end
> ::exit::
>   return ret
> end

  Why the goto?  Why not?
  
	function _get_fx_name(fx,t)
	  for k,v in pairs(t) do
	    if fx == v then
	      return k
	    else
	      if type(v) == 'table' and k ~= '_G' and k ~= 'package' then
	        local name = _get_fx_name(fx,v)
	        if name then return name end
	      end
	    end
	  end
	end

  If nothng if sound, _get_fx_name() will return nothing, which is converted
to a nil, so that case is handled as well.

> function get_fx_name(fx)
>   local name
>   name = _get_fx_name(fx, _ENV)
>   name = name or "unknown function"
>   return name
> end

	function get_fx_name(fx)
	  return _get_fx_name(fx,_ENV) or "unknown name"
	end

  -spc (Untested code, but it should work ... )