script.lua (2740B)
1 local lfs = require( "lfs" ) 2 local serialize = require( "serialize" ) 3 4 local ScriptsDir = os.getenv( "HOME" ) .. "/.mudgangster/scripts" 5 6 package.path = package.path .. ";" .. ScriptsDir .. "/?.lua" 7 8 local function loadScript( name, path, padding ) 9 local function throw( err ) 10 if err:match( "^" .. path ) then 11 err = err:sub( path:len() + 2 ) 12 end 13 14 mud.print( "#lr%-" .. padding .. "s", name ) 15 mud.print( "#s\n>\n> %s\n>", err ) 16 end 17 18 mud.print( "#s\n> " ) 19 20 local mainPath = path .. "/main.lua" 21 local readable, err = io.readable( mainPath ) 22 23 if not readable then 24 throw( err ) 25 26 return 27 end 28 29 local env = setmetatable( 30 { 31 require = function( requirePath, ... ) 32 return require( "%s.%s" % { name, requirePath }, ... ) 33 end, 34 35 saved = function( defaults ) 36 local settingsPath = path .. "/settings.lua" 37 38 mud.listen( "shutdown", function() 39 local file = io.open( settingsPath, "w" ) 40 41 file:write( serialize.unwrapped( defaults ) ) 42 43 file:close() 44 end ) 45 46 local settingsEnv = setmetatable( { }, { 47 __newindex = defaults, 48 } ) 49 50 local settings = loadfile( settingsPath, "t", settingsEnv ) 51 52 if not settings then 53 return defaults 54 end 55 56 if _VERSION == "Lua 5.1" then 57 setfenv( settings, settingsEnv ) 58 end 59 60 pcall( settings ) 61 62 return defaults 63 end, 64 }, 65 { 66 __index = _G, 67 __newindex = _G, 68 } 69 ) 70 71 local script, err = loadfile( mainPath, "t", env ) 72 73 if not script then 74 throw( err ) 75 76 return 77 end 78 79 if _VERSION == "Lua 5.1" then 80 setfenv( script, env ) 81 end 82 83 local loaded, err = pcall( script ) 84 85 if loaded then 86 mud.print( "#lg%s", name ) 87 else 88 throw( err ) 89 end 90 end 91 92 local function loadScripts() 93 mud.print( "#s> Loading scripts..." ) 94 95 local readable, err = io.readable( ScriptsDir ) 96 97 if readable then 98 local attr = lfs.attributes( ScriptsDir ) 99 100 if attr.mode == "directory" then 101 local scripts = { } 102 local maxLen = 0 103 104 for script in lfs.dir( ScriptsDir ) do 105 if not script:match( "^%." ) then 106 local path = ScriptsDir .. "/" .. script 107 local scriptAttr = lfs.attributes( path ) 108 109 if scriptAttr.mode == "directory" then 110 maxLen = math.max( script:len(), maxLen ) 111 112 table.insert( scripts, { 113 name = script, 114 path = path, 115 } ) 116 end 117 end 118 end 119 120 table.sort( scripts, function( a, b ) 121 return a.name < b.name 122 end ) 123 124 for _, script in ipairs( scripts ) do 125 loadScript( script.name, script.path, maxLen ) 126 end 127 else 128 mud.print( "#sfailed!\n> `%s' isn't a directory", ScriptsDir ) 129 end 130 else 131 mud.print( "#sfailed!\n> %s", err ) 132 end 133 134 mud.event( "scriptsLoaded" ) 135 end 136 137 local function closeScripts() 138 end 139 140 return { 141 load = loadScripts, 142 close = closeScripts, 143 }