@@ -27,30 +27,46 @@ var (
2727type Script struct {
2828 lock sync.RWMutex
2929 name string // The name of the script
30+ conc int // The concurrency setting for the VM pool
3031 pool pool // The pool of runtimes for concurrent use
3132 mods []Module // The injected modules
3233 code * lua.FunctionProto // The precompiled code
3334}
3435
35- // FromReader reads a script fron an io.Reader
36- func FromReader (name string , r io.Reader , modules ... Module ) (* Script , error ) {
36+ // New creates a new script from an io.Reader
37+ func New (name string , source io.Reader , concurrency int , modules ... Module ) (* Script , error ) {
38+ if concurrency <= 0 {
39+ concurrency = defaultConcurrency
40+ }
41+
3742 script := & Script {
3843 name : name ,
3944 mods : modules ,
45+ conc : concurrency ,
4046 }
41- return script , script .Update (r )
47+ return script , script .Update (source )
48+ }
49+
50+ // FromReader reads a script fron an io.Reader
51+ func FromReader (name string , r io.Reader , modules ... Module ) (* Script , error ) {
52+ return New (name , r , 0 , modules ... )
4253}
4354
4455// FromString reads a script fron a string
4556func FromString (name , code string , modules ... Module ) (* Script , error ) {
46- return FromReader (name , bytes .NewBufferString (code ), modules ... )
57+ return New (name , bytes .NewBufferString (code ), 0 , modules ... )
4758}
4859
4960// Name returns the name of the script
5061func (s * Script ) Name () string {
5162 return s .name
5263}
5364
65+ // Concurrency returns the concurrency setting of the script
66+ func (s * Script ) Concurrency () int {
67+ return s .conc
68+ }
69+
5470// Run runs the main function of the script with arguments.
5571func (s * Script ) Run (ctx context.Context , args ... any ) (Value , error ) {
5672
@@ -80,7 +96,7 @@ func (s *Script) Update(r io.Reader) (err error) {
8096
8197 // Create a new pool of VMs
8298 s .code = code
83- s .pool , err = newPool (s )
99+ s .pool , err = newPool (s , s . conc )
84100 return
85101}
86102
@@ -200,16 +216,16 @@ func newState() *lua.LState {
200216
201217// --------------------------------------------------------------------
202218
203- // Determine the concurrency for the VM pool
204- var concurrency = int (math .Min (
219+ // defaultConcurrency sets the default concurrency for the VM pool
220+ var defaultConcurrency = int (math .Min (
205221 float64 (runtime .GOMAXPROCS (- 1 )), float64 (runtime .NumCPU ()),
206222))
207223
208224// Pool holds a pool of runtimes.
209225type pool chan * vm
210226
211227// newPool creates a new pool of runtimes.
212- func newPool (s * Script ) (pool , error ) {
228+ func newPool (s * Script , concurrency int ) (pool , error ) {
213229 pool := make (pool , concurrency )
214230 for i := 0 ; i < concurrency ; i ++ {
215231 vm , err := newVM (s )
0 commit comments