| 26 | |
| 27 | namespace agi::lua { |
| 28 | bool LoadFile(lua_State *L, agi::fs::path const& raw_filename) { |
| 29 | auto filename = raw_filename; |
| 30 | try { |
| 31 | filename = agi::fs::Canonicalize(raw_filename); |
| 32 | } |
| 33 | catch (agi::fs::FileSystemUnknownError const& e) { |
| 34 | LOG_E("auto4/lua") << "Error canonicalizing path: " << e.GetMessage(); |
| 35 | } |
| 36 | |
| 37 | agi::read_file_mapping file(filename); |
| 38 | auto buff = file.read(); |
| 39 | auto size = static_cast<size_t>(file.size()); |
| 40 | |
| 41 | // Discard the BOM if present |
| 42 | if (size >= 3 && buff[0] == -17 && buff[1] == -69 && buff[2] == -65) { |
| 43 | buff += 3; |
| 44 | size -= 3; |
| 45 | } |
| 46 | |
| 47 | if (!agi::fs::HasExtension(filename, "moon")) |
| 48 | return luaL_loadbuffer(L, buff, size, filename.string().c_str()) == 0; |
| 49 | |
| 50 | // We have a MoonScript file, so we need to load it with that |
| 51 | // It might be nice to have a dedicated lua state for compiling |
| 52 | // MoonScript to Lua |
| 53 | lua_getfield(L, LUA_REGISTRYINDEX, "moonscript"); |
| 54 | |
| 55 | // Save the text we'll be loading for the line number rewriting in the |
| 56 | // error handling |
| 57 | lua_pushlstring(L, buff, size); |
| 58 | lua_pushvalue(L, -1); |
| 59 | lua_setfield(L, LUA_REGISTRYINDEX, ("raw moonscript: " + filename.string()).c_str()); |
| 60 | |
| 61 | push_value(L, filename); |
| 62 | if (lua_pcall(L, 2, 2, 0)) |
| 63 | return false; // Leaves error message on stack |
| 64 | |
| 65 | // loadstring returns nil, error on error or a function on success |
| 66 | if (lua_isnil(L, 1)) { |
| 67 | lua_remove(L, 1); |
| 68 | return false; |
| 69 | } |
| 70 | |
| 71 | lua_pop(L, 1); // Remove the extra nil for the stackchecker |
| 72 | return true; |
| 73 | } |
| 74 | |
| 75 | static int module_loader(lua_State *L) { |
| 76 | int pretop = lua_gettop(L); |