#!lua require "luanet" -- C#-style using clause: -- luanet.using(expr, function(var) ... end) local IDisposable = luanet.System.Type:GetType('System.IDisposable') local function using_statement(expr,body) assert(IDisposable:IsInstanceOfType(expr), "Expected: IDisposable") pcall(body, expr) expr:Dispose() end -- C#-style using directive: -- luanet.using('System', 'System.IO', 'System.Windows.Forms') local import_type = luanet.import_type local load_assembly = luanet.load_assembly local components local function using_directive(...) local _G = getfenv(3) -- 3:caller() 2:using() 1:using_directive() if not getmetatable(_G) then local m = {} function m:__index(name) print("_G",name) for i = 1,table.getn(components) do local n = components[i] .. "." .. name print("try",n) load_assembly(n) local ty = import_type(n) if ty then print("found",n) rawset(self, name, ty) return ty end end return nil end setmetatable(_G, m) components = {} end for i = 1,table.getn(arg) do local c = arg[i] if type(c) ~= "string" then assert(type(c) == "table", "Expected type name or reference") c = rawget(c, '.fqn') end --load_assembly(c) table.insert(components, c) end return using_directive end -- Is this a directive or a clause? local function using(a,...) if type(a)=="string" or type(a)=="table" then return using_directive(a, unpack(arg)) else return using_statement(a, unpack(arg)) end end luanet.using = using return using