Skip to content

Lua Calling C#

To access C# userdata from Lua, you will need to create a class that has the bLuaUserData attribute. By default, instances will register all classes with this attribute when they initialize.

[bLuaUserData] // The bLua userdata attribute
public class Character
{
    public int health = 100;

    public void Damage(int damage)
    {
        health -= damage;
    }
}

[bLuaUserData]
public class CharacterFunctionLibrary
{
    public static Character CreateCharacter()
    {
        return new Character();
    }
}

Next, we can add an instance of this Character class to our Lua environment as a global variable. We can also add an instance of our CharacterFunctionLibrary.

instance.SetGlobal("character", new Character());
instance.SetGlobal("CharacterFunctionLibrary", new CharacterFunctionLibrary());

In our Lua code, we can access these userdata objects from anywhere since they are global.

instance.DoString(@"
    character:Damage(10)
    print(character.health)

    local newCharacter = CharacterFunctionLibrary.CreateCharacter()
    newCharacter:Damage(20)
    print(newCharacter.health)
");