summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorunwox <me@unwox.com>2024-09-27 15:31:54 +0600
committerunwox <me@unwox.com>2024-09-27 15:31:54 +0600
commit51872975d12c358b2ff0af9f78cda3c9490e486d (patch)
tree69a3f0f2308fe9cc4210d9f500ec2238db47cad5
parent103bd082143565adae273e23e46e8067431eea22 (diff)
support passing CLI arguments to lua script
-rw-r--r--main.go8
-rw-r--r--worker.go27
2 files changed, 26 insertions, 9 deletions
diff --git a/main.go b/main.go
index eaa3ec6..9a2ad52 100644
--- a/main.go
+++ b/main.go
@@ -23,11 +23,11 @@ func main() {
wrksNum := flag.Int("n", runtime.NumCPU(), "Number of HTTP-workers to start")
flag.Parse()
- if flag.NArg() != 1 {
+ if flag.NArg() == 0 {
printUsage()
}
- luaExe := flag.Arg(0)
- mustExist(luaExe)
+ luaArgv := flag.Args()
+ mustExist(luaArgv[0])
httpClient := &http.Client{}
@@ -346,7 +346,7 @@ func main() {
wrk := NewWorker()
wrks = append(wrks, wrk)
go func () {
- err := wrk.Start(luaExe, module)
+ err := wrk.Start(luaArgv, module)
if err != nil {
log.Fatal(err)
}
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
}