lua-gdextension icon indicating copy to clipboard operation
lua-gdextension copied to clipboard

Add support for calling methods in LuaTable

Open gilzoide opened this issue 2 years ago • 3 comments

One way for calling methods in tables is getting the function out of it, and then calling the function manually passing the table as first argument. We could have an easier way to do this, like a call_method method that would allow people to easily call Lua methods.

gilzoide avatar Sep 28 '23 11:09 gilzoide

Do the docs have any example for this? I have been trying to implement an architecture like Love2D, where the lua script must implement callbacks that are on said tables, i.e.

mod.process()
     -- do something
end

and on the gd side run whats inside the mod table on process function

Visnicio avatar May 08 '25 17:05 Visnicio

I figured a way out to define a table before hands but I dont know if its the intended solution, but for those wondering how heres a quick overview:

var lua_vm: LuaState = LuaState.new() # creates a new lua vm/state to work with
var update_callback: LuaFunction # defines a variable that will hold a lua function

func _ready() -> void:
	lua_vmopen_libraries() # just open std libs from lua
	var callbacks_table: LuaTable # will be our reference later for the table containing the callbacks

        lua_vm.globals["callbacks"] = lua_vm.create_table() # will create a new global table on the VM, where we can handle on the lua side
        lua_vm.do_file("res://path-to/a/script.lua") # im loading this from the game's res folder
        callbacks_table = mod_vm.globals["callbacks"] # getting our refence back
        update_callback = api_table["process"] # will expect a callbacks.process on the lua script


func _process(delta: float) -> void:
       update_callback.invoke() # best to do a LuaError check here, but you shall see that the script is invoking our LuaFunction

for reference, heres the lua script

function callbacks.process()
    print("processfunction called") -- you may see this pop up on the godot console
end

Visnicio avatar May 08 '25 18:05 Visnicio

Hey @Visnicio. So this issue is actually about calling methods in Lua tables as if using the : method call syntax from Lua:

some_table:method(...)
-- Is the same as:
some_table.method(some_table, ...)

Right now, in GDScript, one needs to manually pass the table as the method's first argument:

some_table.method.invoke(some_table, ...)

What I was thinking is to add a "call_method" method that would be the same as calling methods with : in Lua:

some_table.call_method("method", ...)

Not sure if this would help or make people even more confused 🤔

Anyway, invoking functions from tables is trivial, just as you already found out:

some_table.lua_func.invoke(...)

gilzoide avatar May 08 '25 20:05 gilzoide

Closing this issue, I don't really think this should be implemented anymore.

gilzoide avatar Jun 18 '25 02:06 gilzoide