Error while calling functions of another script
xanall9766 opened this issue · 3 comments
I made a custom module loading in MoonSharp to load modules and the globals. The module is being loaded
Error
An error occured while executing script: chunk_1:(1,0-47):
Attempt to perform operations with resources owned by different scripts.
Script:
local module = Modules.LoadModule("module.lua")
module.Foo()
module.lua
module = {}
function module.Foo()
Logger.Log("Bar!", "green")
end
return module
Full method LoadModule
public DynValue LoadModule(Script script, string name)
{
string full = ScriptManager.Instance.ScriptsDirectory + "\\" + name;
if (!File.Exists(full))
{
Logger.Log("Cannot find", ConsoleColor.Red);
return DynValue.Nil;
}
FileInfo scriptFile = new FileInfo(full);
if (scriptFile.Extension != ".lua")
{
Logger.Log("Wrong extension", ConsoleColor.Red);
return DynValue.Nil;
}
Script module = new Script();
ScriptManager.Instance.LoadGlobals(module);
DynValue moduleReturn = module.DoString(File.ReadAllText(scriptFile.FullName));
DynValue moduleTable = DynValue.NewTable(script);
foreach (DynValue e in moduleReturn.Table.Keys)
{
moduleTable.Table.Set(e.ToPrintString(), moduleReturn.Table.Get(e));
}
return moduleTable;
}
At present you're creating a new Script
for the each Lua file. Each Script
is essentially its own VM, so you're getting this error because you're trying to interact with Lua values that exist in another VM.
You could call LoadFile
on the existing Script
. However, there's built-in support for what you're after via https://www.moonsharp.org/scriptloaders.html
You could call
LoadFile
on the existingScript
.
I tried LoadFile
right now and i got an exception:
System.Exception: Cannot load script 'module.lua'. By default, scripts should be .txt files placed under a
Assets/Resources/MoonSharp/Scripts directory.
If you want scripts to be put in another directory or another way, use a custom instance of UnityAssetsScriptLoader or
implement your own IScriptLoader (possibly extending ScriptLoaderBase).
I'm not using the UnityAssetsScriptLoader
script.Options.ScriptLoader = new FileSystemScriptLoader();
((ScriptLoaderBase)script.Options.ScriptLoader).ModulePaths = new string[] { "?.lua" };
And loading
DynValue moduleResult = module.LoadFile(scriptFile.FullName);
However, there's built-in support for what you're after via
if there's a way to load globals in require
...
if there's a way to load globals in
require
...
Yes, this is how require
works by default in Lua, MoonSharp included. You'll want to setup a ScriptLoader
as per the link above.
Please try the Discord server for any further questions.