Skip to content

Instantly share code, notes, and snippets.

@javierguerragiraldez
Created April 22, 2015 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javierguerragiraldez/5f4beedc22d8a0c73f0b to your computer and use it in GitHub Desktop.
Save javierguerragiraldez/5f4beedc22d8a0c73f0b to your computer and use it in GitHub Desktop.
sandbox-like app loader
local loader = require 'loader'
local app1 = loader.app('apps.simple_app', { pciaddress='0000:83:00.1', name='app1' })
local app2 = loader.app('apps.simple_app', { pciaddress='0000:83:00.2', name='app2' })
local app3 = loader.app('apps.simple_app', { pciaddress='0000:83:01.1', name='app3' })
app1.selftest()
app2.selftest()
app3.selftest()
loader.set_link(app1, 'tx', app2, 'rx')
loader.set_link(app2, 'tx', app3, 'rx')
loader.set_link(app3, 'tx', app1, 'rx')
for _ = 1, 3 do
app1.push()
app2.push()
app3.push()
end
local loader = {}
-- loads 'dot.named' app
-- 'args' (optional) becomes the initial instance space
-- returns args or (nil, error)
-- safe version, file, syntax or initialization errors are captured
function loader.load_app(appname, args)
local path, errmsg = package.searchpath(appname, package.path)
if not path then return path, errmsg end
args = args or {}
if not getmetatable(args) then
package.seeall(args)
end
local chunk, errmsg = loadfile(path, nil, args)
if not chunk then return chunk, errmsg end
local ok, errmsg = pcall(chunk)
if not ok then return nil, errmsg end
return args
end
-- same as load_app() but (re)raises errors
function loader.app(appname, args)
return assert(loader.load_app(appname, args))
end
-- creates a link and injects into the given apps
-- with the given names in the 'input' and 'output' tables
function loader.set_link(src_app, srcname, dst_app, dstname)
local link = link.new(dst_app)
src_app.output = src_app.output or {}
src_app.output[srcname] = link
dst_app.input = dst_app.input or {}
dst_app.input[dstname] = link
return link
end
return loader
-- arguments are available as variables
print ("initialization time", name, pciaddress)
namecopy1 = name -- "global" vars are instance fields
local namecopy2 = name -- local vars are private
-- define expected functions in the instance space
function push()
print ("pushing packets:", namecopy2) -- local (private) vars are accessible
print (input.rx:nreadable()) -- links are set in 'input' and 'output' tables
end
function selftest()
print ("testing app", namecopy1)
assert(input == nil, "shouldn't have input yet")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment