diff options
| author | unwox <me@unwox.com> | 2024-09-27 15:31:54 +0600 |
|---|---|---|
| committer | unwox <me@unwox.com> | 2024-09-27 15:31:54 +0600 |
| commit | 51872975d12c358b2ff0af9f78cda3c9490e486d (patch) | |
| tree | 69a3f0f2308fe9cc4210d9f500ec2238db47cad5 /worker.go | |
| parent | 103bd082143565adae273e23e46e8067431eea22 (diff) | |
support passing CLI arguments to lua script
Diffstat (limited to 'worker.go')
| -rw-r--r-- | worker.go | 27 |
1 files changed, 22 insertions, 5 deletions
@@ -52,10 +52,13 @@ func NewWorker() *Worker { // Start starts the worker: // 1) creates a Lua context -// 2) executes the filename in it +// 2) executes the argv in it // 3) initiates the the "luna" module so it's possible to call Go functions // from Lua -func (w *Worker) Start(filename string, module map[string]any) error { +func (w *Worker) Start(argv []string, module map[string]any) error { + if len(argv) == 0 { + return errors.New("argv must at least contain lua file name") + } w.mu.Lock() defer w.mu.Unlock() @@ -65,14 +68,28 @@ func (w *Worker) Start(filename string, module map[string]any) error { w.lua.Start() defer w.lua.RestoreStackFunc()() - // registers the module in the Lua context - err := w.lua.PushObject(module) + // emulate passing arguments to the loaded chunk + args := []any{} + if len(argv) > 1 { + for _, arg := range argv[1:] { + args = append(args, arg) + } + } + err := w.lua.PushArray(args) + if err != nil { + return err + } + w.lua.SetGlobal("arg") + + // register the module in the Lua context + err = w.lua.PushObject(module) if err != nil { return err } w.lua.SetGlobal("luna") - err = w.lua.Require(filename) + err = w.lua.Require(argv[0]) + if err != nil { return err } |
