The UserData class allows CLR objects to be exposed to Lua scripts. It provides a bridge between C# and Lua, enabling Lua code to interact with C# objects.
using SolarSharp.Interpreter;using SolarSharp.Interpreter.DataTypes;using SolarSharp.Interpreter.Interop;// Define a C# classpublic class Player{ public string Name { get; set; } public int Health { get; set; } public int MaxHealth { get; set; } public void TakeDamage(int amount) { Health = Math.Max(0, Health - amount); } public void Heal(int amount) { Health = Math.Min(MaxHealth, Health + amount); }}// Register the typeUserData.RegisterType<Player>();var script = new Script();// Create and expose a Player instancevar player = new Player{ Name = "Hero", Health = 100, MaxHealth = 100};script.Globals["player"] = UserData.Create(player);// Use from Luascript.DoString(@" print(player.Name) -- Hero print(player.Health) -- 100 player:TakeDamage(30) print(player.Health) -- 70 player:Heal(20) print(player.Health) -- 90 player.Health = 50 -- Direct property access print(player.Health) -- 50");// Expose static membersUserData.RegisterType<Math>();script.Globals["Math"] = UserData.CreateStatic<Math>();script.DoString(@" local result = Math.Sqrt(16) print(result) -- 4");// Configure access mode for securityUserData.RegisterType<SecureData>(InteropAccessMode.HideMembers);