Skip to content

C# Calling Lua

To access Lua from C#, we first need to define some Lua functions in code and run that code on our instance.

instance.DoString(@"
    function healCharacter(character)
        local healthBefore = character.health
        character.health = 100
        print('Healed character from ', healthBefore, ' to ', character.health)
    end
");

Now we need to get a reference to our healCharacter function in C#.

bLuaValue healFunction = instance.GetGlobal("healCharacter");

Let's do some safety checks to make sure the function is valid, and then call it with a Character passed as a parameter.

if (healFunction != null && healFunction.Type == DataType.Function)
{
    Character newCharacter = new Character();
    newCharacter.Damage(50);
    instance.Call(healFunction, newCharacter);
}