Search code examples
c#genericsargumentsmonogamenlua

C# NLua: Accessing generic parameters


I have an Entity component system using generic parameters. I am trying to get Lua scripting to work using NLua.

However I do not know how to access a generic parameter from the Lua environment.

Something like this?:

if e:HasComponent<Position>() then
    print("Found position...")
end

If there is no way to do this then how would I go about making the components accessible via strings?

Code snippets will be given on request as I do not think it is a problem with my code.


Solution

  • You can try to call the Generic method directly, without the type parameter, NLua will try to match the method name.

    if e:HasComponent () then
        ...
    end
    

    If it fails you can also try to wrap you generic method into a non-generic extension method.

    public static HasPositionComponent (this TypeE e)
    {
         return e.HasComponent<Position>();
    }
    

    Then you can call HasPositionComponent as a regular method from Lua

    if e:HasPositionComponent () then
        ...
    end
    

    Take a look at the GenericMethod test:

    https://github.com/NLua/NLua/blob/main/tests/src/LuaTests.cs#L442