webmcp

diff framework/bin/mcp.lua @ 309:4e69ce9a6365

Mechanism to load, compile, and cache Lua code from the filesystem
author jbe
date Sun Mar 22 22:25:37 2015 +0100 (2015-03-22)
parents 0a6378afc6da
children 9fef75a02542
line diff
     1.1 --- a/framework/bin/mcp.lua	Sun Mar 22 20:39:13 2015 +0100
     1.2 +++ b/framework/bin/mcp.lua	Sun Mar 22 22:25:37 2015 +0100
     1.3 @@ -20,6 +20,36 @@
     1.4  _ENV = setmetatable({}, global_metatable)
     1.5  
     1.6  --[[--
     1.7 +lua_func =   -- compiled Lua function
     1.8 +loadcached(
     1.9 +  filename   -- path to a Lua source or byte-code file
    1.10 +)
    1.11 +
    1.12 +Loads, compiles and caches a Lua chunk. If the file does not exist, nil and an error string are returned. Otherwise the file is loaded, compiled, and cached. The cached value (i.e. the compiled function) is returned. An error is raised if the compilation was not successful.
    1.13 +
    1.14 +--]]--
    1.15 +do
    1.16 +  local cache = {}
    1.17 +  function loadcached(filename)
    1.18 +    local file, read_error = io.open(filename, "r")
    1.19 +    if file then
    1.20 +      local filedata = assert(file:read("*a"))
    1.21 +      assert(file:close())
    1.22 +      local func, compile_error = load(filedata, "=" .. filename, nil, _ENV)
    1.23 +      if func then
    1.24 +        cache[filename] = func
    1.25 +        return func
    1.26 +      else
    1.27 +        error(compile_error, 0)
    1.28 +      end
    1.29 +    else
    1.30 +      return nil, read_error
    1.31 +    end
    1.32 +  end
    1.33 +end
    1.34 +--//--
    1.35 +
    1.36 +--[[--
    1.37  WEBMCP_MODE
    1.38  
    1.39  A constant set to "listen" in case of a network request, or set to "interactive" in case of interactive mode.
    1.40 @@ -139,17 +169,10 @@
    1.41      setmetatable(self, autoloader_mt)
    1.42    end
    1.43    local function try_exec(filename)
    1.44 -    local file = io.open(filename, "r")
    1.45 -    if file then
    1.46 -      local filedata = file:read("*a")
    1.47 -      io.close(file)
    1.48 -      local func, errmsg = load(filedata, "=" .. filename, nil, _ENV)
    1.49 -      if func then
    1.50 -        func()
    1.51 -        return true
    1.52 -      else
    1.53 -        error(errmsg, 0)
    1.54 -      end
    1.55 +    local func = loadcached(filename)
    1.56 +    if func then
    1.57 +      func()
    1.58 +      return true
    1.59      else
    1.60        return false
    1.61      end

Impressum / About Us