From 51872975d12c358b2ff0af9f78cda3c9490e486d Mon Sep 17 00:00:00 2001 From: unwox Date: Fri, 27 Sep 2024 15:31:54 +0600 Subject: support passing CLI arguments to lua script --- worker.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) (limited to 'worker.go') diff --git a/worker.go b/worker.go index 2df98a0..88737f7 100644 --- a/worker.go +++ b/worker.go @@ -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 } -- cgit v1.2.3