Skip to content

Instantly share code, notes, and snippets.

@Yukitty
Created August 19, 2017 15:06
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 Yukitty/2ec9607c1cdf33acf1d987c9f11795ce to your computer and use it in GitHub Desktop.
Save Yukitty/2ec9607c1cdf33acf1d987c9f11795ce to your computer and use it in GitHub Desktop.
-- The complete package library as relevant to possible SRB2 implementation --
-- (pseudocode, but reference Lua 5.3)
-- global package table
package = {
preload = {},
loaded = {},
searchers = {}
}
-- These searcher functions will be used below.
-- They are intended to return a Lua function that represents the script file, and an optional error message.
local function search_preload(name)
return package.preload[name]
end
local function search_lumps(name)
-- load Lua script lump from loaded wads
local chunk, msg = load(name)
return chunk, msg or "lump '"..name.."' not found"
end
-- Lua users can add their own script finders to the list.
-- This is probably not useful to SRB2.
package.searchers = { search_preload, search_lumps }
function require(name)
-- check package.loaded first
if package.loaded[name] then
-- return previous value
return package.loaded[name]
end
local chunk, elist = nil, "Search for '"..name.."' failed:"
for i, search in ipairs(package.searchers) do
local msg
chunk, msg = search(name)
if chunk then
-- found a chunk!
break
end
if msg then
-- append an error
elist = elist .. "\n\t" .. msg
end
end
-- if we've exhausted our list of searchers and not found a chunk,
-- then admit failure and dump all the combined errors we've been saving.
if not chunk then
error(elist)
end
-- Do make sure to check that chunk is a function,
-- and not some random value a user threw into package.preload
assert(type(chunk) == "function")
-- run the script and save its return value
package.loaded[name] = chunk()
-- package.loaded must only contain non-false values,
-- even if the script explicitly returns false or 0
if not package.loaded[name] then
package.loaded[name] = true
end
-- return the value the script gave us
return package.loaded[name]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment