Set source name to full file path in Luau require

This commit is contained in:
Alex Orlenko 2022-06-29 00:53:07 +01:00
parent 9596b97faa
commit 70e16b51ae
No known key found for this signature in database
GPG key ID: 4C150C250863B96D
2 changed files with 15 additions and 7 deletions

View file

@ -85,10 +85,12 @@ fn lua_require(lua: &Lua, name: Option<std::string::String>) -> Result<Value> {
search_path = "?.luau;?.lua".into();
}
let mut source = None;
let (mut source, mut source_name) = (None, String::new());
for path in search_path.split(';') {
if let Ok(buf) = std::fs::read(path.replacen('?', &name, 1)) {
let file_path = path.replacen('?', &name, 1);
if let Ok(buf) = std::fs::read(&file_path) {
source = Some(buf);
source_name = file_path;
break;
}
}
@ -96,7 +98,7 @@ fn lua_require(lua: &Lua, name: Option<std::string::String>) -> Result<Value> {
let value = lua
.load(&source)
.set_name(&format!("={}", name))?
.set_name(&format!("={}", source_name))?
.set_mode(ChunkMode::Text)
.call::<_, Value>(())?;

View file

@ -15,8 +15,11 @@ fn test_require() -> Result<()> {
fs::write(
temp_dir.path().join("module.luau"),
r#"
counter = counter or 0
return counter + 1
counter = (counter or 0) + 1
return {
counter = counter,
error = function() error("test") end,
}
"#,
)?;
@ -24,9 +27,12 @@ fn test_require() -> Result<()> {
lua.load(
r#"
local module = require("module")
assert(module == 1)
assert(module.counter == 1)
module = require("module")
assert(module == 1)
assert(module.counter == 1)
local ok, err = pcall(module.error)
assert(not ok and string.find(err, "module.luau") ~= nil)
"#,
)
.exec()