moonsharp icon indicating copy to clipboard operation
moonsharp copied to clipboard

Table.Get does not respect __index?

Open DaZombieKiller opened this issue 8 years ago • 2 comments

I've noticed that Table.Get doesn't appear to respect the __index metamethod. If this is intentional, is there any way to retrieve a value from a table, respecting metamethods, without needing to use Lua itself?

var script = new Script(CoreModules.Preset_Complete);

var t1 = new Table(script)
{
    ["test"] = 100,
};

var t2 = new Table(script)
{
    MetaTable = new Table(script)
    {
        ["__index"] = t1,
    }
};

Console.WriteLine(t2.Get("test")?.Number); // 0, should be 100

DaZombieKiller avatar Aug 05 '17 07:08 DaZombieKiller

I'm hitting this, too. In actual lua, from C++ you could call lua_getfield, which would trigger the metatable lookup. MoonSharp doesn't appear to do this, even though it has the RawGet vs Get set up. I've written an extension method for this:

public static class MoonsharpExtensions
{
    public static DynValue GetField(this Table table, DynValue key)
    {
        var get = table.Get(key);
        if (get.IsNil() && table.MetaTable != null && table.MetaTable.Get("__index").IsNotNil())
        {
            var index = table.MetaTable.Get("__index");
            if (index.Table != null)
            {
                get = index.Table.Get(key);
            }
            else if (index.Function != null)
            {
                get = index.Function.Call(key);
            }
        }
        return get;
    }
}

Numsgil avatar Feb 25 '18 14:02 Numsgil

agree

Clevergua avatar Jul 18 '21 09:07 Clevergua