is custom package.loaders a bad idea?
Posted: Thu Sep 28, 2023 3:07 pm
Hey y'all, I'm playing around with the driver parts of my application, just trying new things out, and I ended up making this little loader which allows using `require` to load non-lua (non-code) files, kind of like we do in webpack.
Using it, you're able to do the following:
This feels nice and not too clever, which makes me concerned, because I can find almost no references to anything much like this in the forums or wiki, which makes me think this must be a bad idea for reasons that I don't understand, otherwise I imagine folk would stumble into it and talk about it.
As such, as this a bad idea?
Thanks, y'all!
- Jon
Using it, you're able to do the following:
Code: Select all
-- insert just before normal loader
-- glsl is the file extension, newShader is the callback (gets the file content)
table.insert(package.loaders, 2, extension_loader("glsl", love.graphics.newShader))
function love.load()
myshader = require("some.mod.path!glsl")
-- note the path, myshader is a shader object
end
As such, as this a bad idea?
Code: Select all
local extension_loader = function(ext, cb)
return function(modname)
-- only handle paths that end in !ext (eg. my.mod.effect!glsl)
if (not string.find(modname, "!"..ext.."$")) then
return nil
end
-- normalize the path
local modpath = modname
modpath = string.gsub(modpath, "%.", "/")
modpath = string.gsub(modpath, "!", ".")
-- read and return a partially applied callback
local content, _ = love.filesystem.read(modpath)
if content then
return function() cb(content) end, modpath
else
return "no file found named `"..modpath.."` (using `"..ext.."` loader)"
end
end
end
- Jon