Search code examples
f#funscript

How to pass arguments to funscript function?


Is it possible to pass data generated locally in F# to the expression that's being compiled in Funscript?

Example of what I mean:

let MyJSFunc str () =
    Globals.alert str

let myStr = File.ReadAllText "somefile.txt"

Compiler.Compiler.Compile(<@ MyJSFunc myStr () @>,noReturn=true)

If I use a static string instead of reading it from a local file it works, so my guess is that Funscript tries to compile the file reading to JS, even though the file has already been read by the time it reaches the compilation?


Solution

  • FunScript attempts to translate the code of all top-level declarations. As you mentioned, this includes thy MyJSFunc function but also the myStr value (which is not possible as it accesses the file system).

    One way to solve this is to turn myStr into a local declaration. That way, the F# will store its value in the quotation (rather than storing the definition):

    let MyJSFunc str () =
        Globals.alert str
    
    let translate () =
      let myStr = File.ReadAllText "somefile.txt"
      Compiler.Compiler.Compile(<@ MyJSFunc myStr () @>,noReturn=true)
    

    Another way to do the same thing is to use quotation splicing and create a quoted value explicitly using Expr.Value:

    open Microsoft.FSharp.Quotations
    
    Compiler.Compiler.Compile(<@ MyJSFunc (%Expr.Value(myStr)) () @>,noReturn=true)