Skip to content

LuaState with "user context" for passing references to C# LuaFunction #202

@CodeSmile-0000011110110111

Description

More than once I would have found it useful for some C#-specific "userdata" object attached to the LuaState itself (unavailable to Lua).

I noticed there is a commented AdditionalContext property in LuaFunctionExecutionContext:

//public object? AdditionalContext { get; init; }

Is this planned to be added?

When Lua calls a C# method, the LuaFunction context is "static" so it's difficult to call into the C# API.
My use-case is an object factory which instantiates the correct Lua wrapper for component based on the component's C# type.

Right now I just have my factory in the global Lua state and need to read it from the Environment table:

var component = AddComponent(type);

var factory = context.State.Environment[nameof(LuaObjectFactory)].Read<LuaObjectFactory>();

var luaValue = factory.CreateLuaInstance(component);
context.Return(luaValue);

Would be nice if I could hide that implementation detail (factory) and to avoid risking that factory getting erased by a simple assignment. Like with the AdditionalContext property for instance:

var component = AddComponent(type);

var factory = ((MyStateData)context.State.AdditionalContext).Factory;

var luaValue = factory.CreateLuaInstance(component);
context.Return(luaValue);

PS: I would call it UserContext, in-line with UserData.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions