moonsharp
moonsharp copied to clipboard
Table.Get does not respect __index?
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
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;
}
}
agree