package math import luajit "git.sharkk.net/Sky/LuaJIT-to-Go" // GetMathFunctions returns all math-related Go functions func GetMathFunctions() map[string]luajit.GoFunction { return map[string]luajit.GoFunction{ "math_factorial": func(s *luajit.State) int { if err := s.CheckMinArgs(1); err != nil { return s.PushError("math_factorial: %v", err) } n, err := s.SafeToNumber(1) if err != nil || n < 0 || n != float64(int(n)) { return s.PushError("math_factorial: argument must be a non-negative integer") } if n > 170 { return s.PushError("math_factorial: argument too large (max 170)") } result := 1.0 for i := 2; i <= int(n); i++ { result *= float64(i) } s.PushNumber(result) return 1 }, "math_gcd": func(s *luajit.State) int { if err := s.CheckExactArgs(2); err != nil { return s.PushError("math_gcd: %v", err) } a, err := s.SafeToNumber(1) if err != nil || a != float64(int(a)) { return s.PushError("math_gcd: first argument must be an integer") } b, err := s.SafeToNumber(2) if err != nil || b != float64(int(b)) { return s.PushError("math_gcd: second argument must be an integer") } ia, ib := int(a), int(b) for ib != 0 { ia, ib = ib, ia%ib } s.PushNumber(float64(ia)) return 1 }, "math_lcm": func(s *luajit.State) int { if err := s.CheckExactArgs(2); err != nil { return s.PushError("math_lcm: %v", err) } a, err := s.SafeToNumber(1) if err != nil || a != float64(int(a)) { return s.PushError("math_lcm: first argument must be an integer") } b, err := s.SafeToNumber(2) if err != nil || b != float64(int(b)) { return s.PushError("math_lcm: second argument must be an integer") } ia, ib := int(a), int(b) // Calculate GCD gcd := func(x, y int) int { for y != 0 { x, y = y, x%y } return x } result := ia * ib / gcd(ia, ib) s.PushNumber(float64(result)) return 1 }, } }