60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package luajit
|
|
|
|
import "fmt"
|
|
|
|
// ArgSpec defines an argument specification for validation
|
|
type ArgSpec struct {
|
|
Name string
|
|
Type string
|
|
Required bool
|
|
Check func(*State, int) bool
|
|
}
|
|
|
|
// Common argument checkers
|
|
var (
|
|
CheckString = func(s *State, i int) bool { return s.IsString(i) }
|
|
CheckNumber = func(s *State, i int) bool { return s.IsNumber(i) }
|
|
CheckBool = func(s *State, i int) bool { return s.IsBoolean(i) }
|
|
CheckTable = func(s *State, i int) bool { return s.IsTable(i) }
|
|
CheckFunc = func(s *State, i int) bool { return s.IsFunction(i) }
|
|
CheckAny = func(s *State, i int) bool { return true }
|
|
)
|
|
|
|
// CheckArgs validates function arguments against specifications
|
|
func (s *State) CheckArgs(specs ...ArgSpec) error {
|
|
for i, spec := range specs {
|
|
argIdx := i + 1
|
|
if argIdx > s.GetTop() {
|
|
if spec.Required {
|
|
return fmt.Errorf("missing argument %d: %s", argIdx, spec.Name)
|
|
}
|
|
break
|
|
}
|
|
|
|
if s.IsNil(argIdx) && !spec.Required {
|
|
continue
|
|
}
|
|
|
|
if !spec.Check(s, argIdx) {
|
|
return fmt.Errorf("argument %d (%s) must be %s", argIdx, spec.Name, spec.Type)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CheckMinArgs checks for minimum number of arguments
|
|
func (s *State) CheckMinArgs(min int) error {
|
|
if s.GetTop() < min {
|
|
return fmt.Errorf("expected at least %d arguments, got %d", min, s.GetTop())
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CheckExactArgs checks for exact number of arguments
|
|
func (s *State) CheckExactArgs(count int) error {
|
|
if s.GetTop() != count {
|
|
return fmt.Errorf("expected exactly %d arguments, got %d", count, s.GetTop())
|
|
}
|
|
return nil
|
|
}
|