rosbit/luago

Have Go Struct functions available in Lua

Closed this issue · 4 comments

Hi!

This is very nifty little project! I took a look at this and it sure does have some nifty pieces to glue Go and Lua together.

However, I would like to be able to register a struct and it's functions to be available in Lua as well. Maybe even be able to create a separate table/package for it and so it can be included using require if wanted?

Now, the ctx.LoadFile looked promising, but it doesn't seem to go through the struct's functions to register them under the global name provided in the environment. Or maybe I missed something?

Like so:

var v Vector2
ctx.LoadFile("test.lua", map[string]any{
 "vector2"; &v,
})

Doing this I was hoping the New() and Add(v2 Vector2) that I have added to the Vector2 struct would be available in Lua as well, but they weren't.

So, this didn't work:
local v = vector2.New()

Any chance you can add this functionality or give me some hints on how to add it myself?

Thanks!

After some more digging, it actually seems one can do:

	var v2 Vector2
	var v3 Vector3

	if err := ctx.LoadFile("vector-test.lua", map[string]any{
		"vector2": map[string]any{"New": New2, "object": &v2},
		"vector3": map[string]any{"New": New3, "object": &v3},
	}); err != nil {
		fmt.Printf("%v\n", err)
	} 

And then:

local v1 = vector2.New()
v1.x = 1
v1.y = 2
print(v1)

local v2 = vector2.New()
v2.x = 1
v2.y = 2
print(v2.x, v2.y)

v1.AddX(3.0)
print(v1.x, v1.y)

vAdd = v1.AddX(5.0)
print(vAdd.x, vAdd.y)

vTotal = v1.Add(v1)
print(vTotal.x, vTotal.y)

Which is pretty cool.

The only "ugly" part is the "object" part where that does some magic to make the methods work. The "object" shouldn't really be used...

Sorry to response your issues so late. Because I don't know what the implementation detail of New2() and New3(), so I just give the following codes to try to remove the ugly object part:

func New2() *Vector2 {
     return &Vector2{}
}

func New3() *Vector3 {
     return &Vector3{}
}

// --- the lua script loader ---
        if err := ctx.LoadFile("vector-test.lua", map[string]any{
		"newVector2": New2,
		"newVector3": New3,
        }); err != nil {
		fmt.Printf("%v\n", err)
        }

Now the lua code:

local v1 = newVector2()
...
local v2 = newVector2()
...
v1.addX(3.0)  -- first letter of function name in lower case is still working.
...

Ah, yes. It just works that way too. Pretty cool. Thanks!