58 lines
959 B
Go
58 lines
959 B
Go
package math
|
|
|
|
import luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
|
|
|
|
func GetFunctionList() map[string]luajit.GoFunction {
|
|
return map[string]luajit.GoFunction{
|
|
"math_factorial": math_factorial,
|
|
"math_gcd": math_gcd,
|
|
"math_lcm": math_lcm,
|
|
}
|
|
}
|
|
|
|
func math_factorial(s *luajit.State) int {
|
|
n := s.ToNumber(1)
|
|
if n < 0 || n != float64(int(n)) || n > 170 {
|
|
s.PushNil()
|
|
s.PushString("invalid argument")
|
|
return 2
|
|
}
|
|
|
|
result := 1.0
|
|
for i := 2; i <= int(n); i++ {
|
|
result *= float64(i)
|
|
}
|
|
|
|
s.PushNumber(result)
|
|
return 1
|
|
}
|
|
|
|
func math_gcd(s *luajit.State) int {
|
|
a := int(s.ToNumber(1))
|
|
b := int(s.ToNumber(2))
|
|
|
|
for b != 0 {
|
|
a, b = b, a%b
|
|
}
|
|
|
|
s.PushNumber(float64(a))
|
|
return 1
|
|
}
|
|
|
|
func math_lcm(s *luajit.State) int {
|
|
a := int(s.ToNumber(1))
|
|
b := int(s.ToNumber(2))
|
|
|
|
// Calculate GCD
|
|
gcd := func(x, y int) int {
|
|
for y != 0 {
|
|
x, y = y, x%y
|
|
}
|
|
return x
|
|
}
|
|
|
|
result := a * b / gcd(a, b)
|
|
s.PushNumber(float64(result))
|
|
return 1
|
|
}
|