Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created November 23, 2012 01:48
Show Gist options
  • Save hpcx82/4133666 to your computer and use it in GitHub Desktop.
Save hpcx82/4133666 to your computer and use it in GitHub Desktop.
Use lua to manipulate functions
LIBS = {}
DEPS = {}
EXPORTS = {'bar'}
bar = {}
function bar.use_nonpopular_bar()
print 'bar.use_nonpopular_bar'
end
LIBS = {}
DEPS = {}
EXPORTS = {'foo'}
foo = {}
function foo.use_nonpopular_foo()
print 'foo.use_nonpopular_foo'
end
LIBS = {}
DEPS = {}
EXPORTS = {'foo'}
foo = {}
function foo.use_nonpopular_foo()
print 'foo.use_nonpopular_foo-2'
end
function foo.use_nonpopular_foo2()
print 'foo.use_nonpopular_foo2'
end
-- load data from file into a separated namespace
local function loaddata(file, setup)
local f,e = loadfile(file)
if not f then error(e, 2) end
-- Create the namespace.
local ns = setmetatable({}, {__index=_G})
setfenv(f, ns)
f()
return ns
end
-- load foo
local nsfoo = loaddata('foo-premake-use.lua')
local exported_name_foo = nsfoo.EXPORTS[1]
print(exported_name_foo)
local exportednsfoo = nsfoo[exported_name_foo]
exportednsfoo.use_nonpopular_foo()
-- bring to global namespace
_G[exported_name_foo] = exportednsfoo
foo.use_nonpopular_foo()
-- load bar
local nsbar = loaddata('bar-premake-use.lua')
local exported_name_bar = nsbar.EXPORTS[1]
print(exported_name_bar)
local exportednsbar = nsbar[exported_name_bar]
exportednsbar.use_nonpopular_bar()
-- bring to global namespace
_G[exported_name_bar] = exportednsbar
bar.use_nonpopular_bar()
-- load foo2 - handle name clashes
local nsfoo2 = loaddata('foo2-premake-use.lua')
local exported_name_foo2 = nsfoo2.EXPORTS[1]
print(exported_name_foo2)
local exportednsfoo2 = nsfoo2[exported_name_foo2]
exportednsfoo2.use_nonpopular_foo()
exportednsfoo2.use_nonpopular_foo2()
-- merge
if _G[exported_name_foo2] then
local t = _G[exported_name_foo2]
for k, v in pairs(exportednsfoo2) do
if t[k] then
-- function conflicts detected
print(k .. ' already exists in table ' .. exported_name_foo2)
else
t[k] = v
end
end
end
-- now foo is brought into the global namespace from premake_use.lua, and get merged from different files
foo.use_nonpopular_foo()
foo.use_nonpopular_foo2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment