Skip to content

Commit

Permalink
feat: get_port func (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcStdt authored Oct 18, 2024
1 parent b4007a0 commit cdeeff0
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
2 changes: 1 addition & 1 deletion examples/minecraft/.scroll/packet_handler/udp.lua
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function handle(ctx, data)

serverPortString = get_var("ServerPort") or "7777"

serverPort = tonumber(serverPortString)
serverPort = get_port("main")

-- hex
nameHex = string.tohex(name)
Expand Down
2 changes: 1 addition & 1 deletion examples/minecraft/.scroll/scroll.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ ports:
value: "Coldstarter is cool (server is idle, join to start)"
- name: ServerPort
value: "7777"
- name: udptest2
- name: main
protocol: udp
port: 12345
sleep_handler: generic
Expand Down
2 changes: 1 addition & 1 deletion internal/core/services/coldstarter.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (c ColdStarter) Start(ctx context.Context, stopAfterFirst bool) error {
vars[v.Name] = v.Value
}

handler = lua.NewLuaHandler(path, c.dir, vars)
handler = lua.NewLuaHandler(path, c.dir, vars, c.ports)
}

if port.Protocol == "udp" {
Expand Down
22 changes: 21 additions & 1 deletion internal/core/services/coldstarter/handler/lua_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package lua
import (
"fmt"

"github.com/highcard-dev/daemon/internal/core/domain"
"github.com/highcard-dev/daemon/internal/core/ports"
"github.com/highcard-dev/daemon/internal/utils/logger"
lua "github.com/yuin/gopher-lua"
Expand All @@ -13,18 +14,20 @@ type LuaHandler struct {
file string
luaPath string
externalVars map[string]string
ports []domain.Port
}

type LuaWrapper struct {
luaState *lua.LState
}

func NewLuaHandler(file string, luaPath string, externalVars map[string]string) *LuaHandler {
func NewLuaHandler(file string, luaPath string, externalVars map[string]string, ports []domain.Port) *LuaHandler {

handler := &LuaHandler{
file: file,
luaPath: luaPath,
externalVars: externalVars,
ports: ports,
}
return handler
}
Expand Down Expand Up @@ -91,6 +94,23 @@ func (handler *LuaHandler) GetHandler(funcs map[string]func(data ...string)) (po
},
))

l.SetGlobal("get_port", l.NewFunction(
func(l *lua.LState) int {
arg := l.CheckString(1)
ports := handler.ports

for _, port := range ports {
if port.Name == arg {
l.Push(lua.LNumber(port.Port))
return 1
}
}

l.Push(lua.LNil)
return 1
},
))

// set package.path to include the luaPath
l.DoString(fmt.Sprintf("package.path = package.path .. ';;%s/?.lua'", handler.luaPath))

Expand Down

0 comments on commit cdeeff0

Please sign in to comment.