lua-users home
lua-l archive

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


Dear list,

I am working on a project where Lua is embedded inside a larger C environment. In a previous version, I had registered some C functions as Lua globals (through lua_register), thus polluting the global scope.

Now I would like to do things right, so I registered the same functions as members of a table (say "lib"), so that they are called as lib.myfun() instead of just myfun().

However, I would like to keep some support for the "global" convention, as I cannot expect all the scripts to be ported to the new convention immediately. But at the same time I would like to print a warning whenever a function is called as global before falling beck to lib.xxx.

I implemented a version that adds a metatable to _G that defines the __index metamethod more or less like the following:

mt = {}

mt.__index = function(table, key)
	if [key is one of a list of possible keys] then
		print("Warning! Deprecated usage")
		return lib[key]
	else
		return nil
	end
end

setmetatable(_G, mt)


I tested it and it seems to work, but I am a bit worried about adding such a metamethod to the global environment. Is it a good idea? Is there some loophole that I might fall into in some cases? Is there a better way of achieving my goal?

Thanks!

Cheers,

Francesco