stevedonovan / luar

luar is a Go package for conveniently working with the luago Lua bindings. Arbitrary Go functions can be registered
MIT License
301 stars 55 forks source link

varargs -- from Lua, calling Go functions with variable argument count #45

Closed glycerine closed 6 years ago

glycerine commented 6 years ago

Well Luar is pretty awesome. I'm really finding it fantastic.

One thing I'm puzzling over at the moment is how to call vararg functions.

For example, given

func SummerAny(a ...int) int {                                                                  
    tot := 0                                                                                    
    for i := range a {                                                                          
        tot += a[i]                                                                             
    }                                                                                           
    return tot                                                                                  
}  

... inside some Go code

    luar.Register(ic.vm, "fmt", luar.Map{                                                       
        "SummerAny": SummerAny,                                                                 
    })   

I've got a Go function, SummerAny that takes a variable number of arguments. I'm trying to call SummerAny from Lua (LuaJIT really, but they are binary compatible). So if I try to pass an array like this:

> print(fmt.SummerAny({1,2,3,4}))  

then luar complains

cannot convert Go function argument #1: cannot convert Lua value 'table: %!p(uintptr=75345376)' (table) to int

If anyone has any suggestions or ideas about how to make this work, I'm open.

glycerine commented 6 years ago

Heh. Well this works:

> print(fmt.SummerAny(1, 2, 3, 4))  
10

I guess I'm trying to get the equivalent of Go's slice... call, i.e. I'd like to say

fmt.SummerAny({1,2,3,4}...)

as one would in Go.

glycerine commented 6 years ago

I guess

fmt.SummerAny(unpack({1, 2, 3, 4}))

will do.