Skip to content

Try read LuaValue#269

Open
ashtonmeuser wants to merge 2 commits intonuskey8:mainfrom
ashtonmeuser:try-read-lua-value
Open

Try read LuaValue#269
ashtonmeuser wants to merge 2 commits intonuskey8:mainfrom
ashtonmeuser:try-read-lua-value

Conversation

@ashtonmeuser
Copy link
Contributor

Return the original ref when calling LuaValue.TryRead<LuaValue>. This is useful for generics where T may be LuaValue.

For example, the consider the following readonly LuaTable that reads from a backing IReadOnlyDictionary<TKey, TValue>. This works as is in all cases except when the key or value type is LuaValue itself.

public static LuaTable ReadOnlyDict<TKey, TValue>(IReadOnlyDictionary<TKey, TValue> backing)
{
    var proxy = new LuaTable();
    var metatable = new LuaTable();

    metatable[Metamethods.Index] = new LuaFunction("__index", (context, ct) =>
    {
        var keyValue = context.GetArgument(1);
        if (!keyValue.TryRead<TKey>(out var key) || !backing.TryGetValue(key, out var value))
            return new(context.Return(LuaValue.Nil));

        return new(context.Return(LuaValue.FromObject(value)));
    });

    metatable[Metamethods.NewIndex] = new LuaFunction("__newindex", (context, ct) =>
        throw new LuaRuntimeException(context.State, $"readonly table: cannot assign key '{context.GetArgument(1)}'"));

    metatable[Metamethods.Metatable] = "readonly";
    proxy.Metatable = metatable;

    return proxy;
}

P.S. I intend to make a PR with some of the collection wrappers I've created like the one above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant