neolithos / neolua

A Lua implementation for the Dynamic Language Runtime (DLR).
https://neolua.codeplex.com/
Apache License 2.0
466 stars 76 forks source link

Extending LuaTable #161

Open thoj opened 1 year ago

thoj commented 1 year ago

NeoLua Version: HEAD

Hi. I was wondering if it's possible to Extend LuaTable.

I have successfully used LuaType.RegisterTypeExtension(typeof(XXXExtensions)); For extending lots of other types. But if i try the same for LuaTable it does not work in Lua.

Extension:

    public static class TableExtensions
    {
        public static string DoSomethingStupid(this LuaTable lt)
        {
            return "Stupid :P";
        }
        public static string DoSomethingStupid2(this DateTime lt)
        {
            return "Stupid :P";
        }
}

Later:

LuaType.RegisterTypeExtension(typeof(TableExtensions));

I can use the extension method in c# but not in Lua, Example to reproduce:

local t = { foo = "bar" };
print(DateTime.Now:DoSomethingStupid2())
print(t:DoSomethingStupid()) 

Result:

Stupid :P
'table:DoSomethingStupid' not found. Neo.IronLua.LuaRuntimeException: 'table:DoSomethingStupid' not found.
   at Neo.IronLua.LuaChunk.Run(LuaTable env, Object[] callArgs)
   at Neo.IronLua.LuaGlobal.DoChunk(LuaChunk chunk, Object[] callArgs)
   at Neo.IronLua.LuaGlobal.LuaDoChunk(Object[] args)
   at CallSite.Target(Closure , CallSite , Object , LuaChunk )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at CallSite.Target(Closure , CallSite , Object , LuaChunk )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
   at NectOPC.NectOPC.ExecuteLua(String scriptfile)
StackTrace:  -- internal --
 at [L] config(LuaTable) line config.lua:11

It is likely that there is a technical reason why this is not working. However, it would be desirable to have the capability to use extnsion methods on LuaTable in Lua.

neolithos commented 1 year ago

LuaTableis because of Lua a little special. But it can extent with MetaTables.

It might be supported with some changes in LuaTableMetaObject.