1 --------------------------------------------------------------------------------
2 -- Copyright (c) 2006-2013 Fabien Fleutot and others.
4 -- All rights reserved.
6 -- This program and the accompanying materials are made available
7 -- under the terms of the Eclipse Public License v1.0 which
8 -- accompanies this distribution, and is available at
9 -- http://www.eclipse.org/legal/epl-v10.html
11 -- This program and the accompanying materials are also made available
12 -- under the terms of the MIT public license which accompanies this
13 -- distribution, and is available at http://www.lua.org/license.html
16 -- Fabien Fleutot - API and implementation
18 --------------------------------------------------------------------------------
20 --*-lua-*-----------------------------------------------------------------------
21 -- Override Lua's default compilation functions, so that they support Metalua
22 -- rather than only plain Lua
23 --------------------------------------------------------------------------------
25 local mlc = require 'metalua.compiler'
30 local original_lua_versions = {
33 loadstring = loadstring,
36 local lua_loadstring = loadstring
37 local lua_loadfile = loadfile
39 function M.loadstring(str, name)
40 if type(str) ~= 'string' then error 'string expected' end
41 if str:match '^\027LuaQ' then return lua_loadstring(str) end
42 local n = str:match '^#![^\n]*\n()'
43 if n then str=str:sub(n, -1) end
44 -- FIXME: handle erroneous returns (return nil + error msg)
45 return mlc.new():src_to_function(str, name)
48 function M.loadfile(filename)
49 local f, err_msg = io.open(filename, 'rb')
50 if not f then return nil, err_msg end
51 local success, src = pcall( f.read, f, '*a')
53 if success then return M.loadstring (src, '@'..filename)
54 else return nil, src end
57 function M.load(f, name)
61 if not x then break end
62 assert(type(x)=='string', "function passed to load() must return strings")
65 return M.loadstring(table.concat(acc))
68 function M.dostring(src)
69 local f, msg = M.loadstring(src)
70 if not f then error(msg) end
74 function M.dofile(name)
75 local f, msg = M.loadfile(name)
76 if not f then error(msg) end
80 -- Export replacement functions as globals
81 for name, f in pairs(M) do _G[name] = f end
83 -- To be done *after* exportation
84 M.lua = original_lua_versions