Scripting Nodes with GDLuau

Godot Version

4.x

Question

Hi, I wonder if anyone can give me some pointers on scripting godot nodes with Luau using the GDLuau extension.

I’d like to have a tinker with user written scripts, but I am a lua novice.

So far, I’ve been able to call some simple lua written in a text file:

-- Called once when the script is attached
function on_ready(node)
	print("on_ready")
	print(type(node))
	print(node:get_name())
end

And in my main node:

extends Node2D

var vm: LuauVM

func _ready() -> void:
	vm = LuauVM.new()
	vm.open_all_libraries()
	vm.stdout.connect(_on_stdout)
	
	var code := FileAccess.get_file_as_string("res://scripts/test.lua.txt")
	if vm.load_string(code, "test") != 0:
		push_error("Lua compile error: %s" % vm.lua_tostring(-1))
		return
		
	if vm.lua_pcall(0, 0, 0) != 0:
		push_error("Lua runtime error: %s" % vm.lua_tostring(-1))
		return

	vm.lua_getglobal("on_ready")
	if vm.lua_isfunction(-1):
		vm.lua_pushobject(self)
		if vm.lua_pcall(1, 0, 0) != 0:
			push_error("Lua runtime error: %s" % vm.lua_tostring(-1))
			return

func _on_stdout(msg: String) -> void:
	print("[Lua]", msg)

So, I can read the lua code as a string, load it into the VM, and a call the on_ready function defined in the lua code.

But, the node passed to the on_ready function is of type userdata. And I haven’t been able to do anything with that. I’d like to be able to call the nodes methods and set it’s properties from the lua script.

node:get_name() fails with an error:
Lua runtime error: [string “test”]:10: attempt to index object with ‘get_name’

Is this possible? Am I nearly there (for a basic proof of concept)? Should I be going about it in a different way? Any help would be great appreciated.