Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to embed function like require #41

Closed
lazytiger opened this issue Sep 24, 2013 · 3 comments
Closed

how to embed function like require #41

lazytiger opened this issue Sep 24, 2013 · 3 comments

Comments

@lazytiger
Copy link

For multiple script files, a require function will be nice, but I have tried and failed.

func require(fn otto.FunctionCall) otto.Value {
file := fn.Argument(0).String()
fmt.Printf("require file:%s\n", file)
data, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
panic(err)
}

_, err = fn.Otto.Run(string(data))
fmt.Println(string(data))
if err != nil {
    fmt.Println(err)
    panic(err)
}

return otto.TrueValue()

}
engine := otto.New()
engine.Set("require", require)

@robertkrimen
Copy link
Owner

You probably want something like this:

package main

import (
    "fmt"
    Otto "github.com/robertkrimen/otto"
    "io/ioutil"
)

func main() {
    otto := Otto.New()
    otto.Set("require", require)
    otto.Run(`
        require("test.js");
        test();
    `)
}

func require(call Otto.FunctionCall) Otto.Value {
    file := call.Argument(0).String()
    fmt.Printf("requiring: %s\n", file)
    data, err := ioutil.ReadFile(file)
    if err != nil {
        fmt.Println(err)
        panic(err)
    }
    _, err = call.Otto.Run(string(data))
    fmt.Println(string(data))
    if err != nil {
        fmt.Println(err)
        panic(err)
    }
    return Otto.TrueValue()
}

I'm not sure if it's a bug that Run does not always run in the global context or not...

@robertkrimen
Copy link
Owner

And here is test.js:

var global = Function('return this')();

global.test = function() {
    console.log("Hello, World.");
};

@ddliu
Copy link

ddliu commented Jun 22, 2014

I've created a package named motto to provide a Nodejs like module environment, hope it helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants