godot_luaAPI icon indicating copy to clipboard operation
godot_luaAPI copied to clipboard

Monitor LuaAPI at the GDS level for changes in LuaAPI

Open Yanxiyimengya opened this issue 1 year ago • 4 comments

Hello my friend, I want to detect the change of the Lua variable in the LuaAPI, just like I wrote the following code in the Lua script by setting the "_newindex" or "index" function of the metatable of the "_G" table, but I want to detect it in the GDS script, is there any way to detect this? just like this:

setmetatable(_G, {
      __index=function(self,idx) if idx==name then return proxy end end;
   })

Or, is there any way I can modify the _G table in Lua via GodotScript?

Yanxiyimengya avatar Feb 25 '24 09:02 Yanxiyimengya

var lua = LuaAPI.new();
lua.do_string("
hp = 10;
function change()
	hp = hp + 1;
end
",[]);

Here's what it looks like: I want to be able to detect in the GDS script when the hp variable is changed in the Lua script For example, when a variable changes, I can connect a signal to detect something like that

Yanxiyimengya avatar Feb 25 '24 09:02 Yanxiyimengya

I know there is something called "LuaObjectMetatable", but I'm declaring a class that inherits from LuaObjectMetatable. I still can't get the expected result when I create a LuaAPI and modify its object_metatable to this class. There is no way to monitor Lua's global variables for changes.

# GodotScript MyLuaObjectMetatable.gd
extends LuaObjectMetatable;
class_name MyLuaObjectMetatable;
func __index(obj : Object, lua: LuaAPI,index: String):
	print(obj, ".", index);
func __newindex(obj : Object, lua: LuaAPI,index: String, value):
	print(obj, ".", index, "." ,value);
# GodotScript Test.gd(Main Scene)
func _ready():
	var lua = LuaAPI.new();
	lua.object_metatable = MyLuaObjectMetatable.new();
	lua.do_string("
	hp = 10;
	function change()
		hp = hp + 1;
	end
	",[]);
	
	lua.call_function("change",[]);

Or rather.... how to use it?

Yanxiyimengya avatar Feb 25 '24 09:02 Yanxiyimengya

So the object_metatable does not get applied to the global table. Currently besides doing it from within lua we do not offer a way to do this. Potentially support could be added though.

The object_metable rather is applied to godot types which inherent from the Object type.

Trey2k avatar Feb 25 '24 13:02 Trey2k

@Yanxiyimengya I haven't tried this yet but what if you did something like this?

var mymetatable := MyLuaObjectMetatable.new()
lua.push_variant("mymetatable", mymetatable)
lua.do_string("setmetatable(_G, mymetatable)")

jbromberg avatar Mar 19 '24 19:03 jbromberg