Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table.Get does not respect __index? #199

Open
DaZombieKiller opened this issue Aug 5, 2017 · 2 comments
Open

Table.Get does not respect __index? #199

DaZombieKiller opened this issue Aug 5, 2017 · 2 comments

Comments

@DaZombieKiller
Copy link

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
@Numsgil
Copy link

Numsgil commented Feb 25, 2018

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;
    }
}

@Clevergua
Copy link

agree

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

No branches or pull requests

3 participants