Loaded library reference has different semantics when embedded

With libraries in the user profile, the following example works:

'  FooLibrary.FooModule '
Function FooFn
  FooFn = "foo result"
End Function

' in another library i.e Standard.Module1 '
Sub Main
  BasicLibraries.LoadLibrary("FooLibrary")
  Foo.FooModule.FooFn()
  x = Foo.Module
  x.FooFn
End Sub

If both of the libraries are embedded in a document instead, or if the Main Sub is in an embedded library, FooModule.FooFn() or Foo.FooModule.FooFn() work, but x.FooFn throws an error: BASIC runtime error. Object variable not set. It appears that the reference made available by LoadLibrary() has different semantics when the calling macro is embedded in a document. When inspecting the references in the IDE, libraries and modules loaded from an embedded macro are always shown as “Out of Scope”, which seems to be related. Is this behavior documented somewhere? Is it a bug?

Does it help to get the script from document.getScriptProvider() as in run libreoffice local macro from python? - Stack Overflow

That would get a function or sub into a variable you could call invoke on… not quite the same, but even that has exactly the same issue when embedded. It works when run from a macro within the user profile, and gets the same “Out of Scope” and “Object variable not set” situation when embedded.

I can’t claim to have the best answer to my question, but I have resolved the error by declaring the variable in advance of assigning the library or module to it.

Sub Main
  BasicLibraries.LoadLibrary("FooLibrary")
  Foo.FooModule.FooFn()
  Dim x as Variant
  x = Foo.Module
  x.FooFn() ' works!
End Sub

So, the difference in behavior may have something to do with the type system, with it being unable to determine the type of x in the way that it does when the macro is not embedded.

Or maybe instead of the type, storage must be allocated for the variable. Just a guess. That would be expected for C++, although not normally for Basic. Anyway, glad you found a solution. My opinion is that a working solution is all you need, not necessarily the best way or an explanation of why it works.