JakobOvrum/LuaD

Lua program crashes when using delegates instead of function pointers

WebFreak001 opened this issue · 3 comments

I didnt try with a clean app but with my engine it crashes (only for other people, I couldn't reproduce it) when i use

// LuaState lua
LuaTable table = lua.newTable();
table["derp"] = () { return player.x; };

When I use derp frequently by calling the lua function which calls derp it will eventually crash after some undefined time. However when I create a function for that and then reference that, it will never crash. Maybe its something with the D garbage collector deleting the lambdas because it thinks it isnt used. So this works:

// LuaState lua
LuaTable table = lua.newTable();
int derp() { return player.x; }
table["derp"] = &derp;

Anonymous functions and (non-static) nested functions should behave exactly the same - they are both delegates, and they both produce closures when that delegate is escaped. Maybe your second example isn't true to exactly what they tried when it worked?

Anyway, LuaD should be handling the GC problem by calling GC.addRoot on the userdata pointer created for delegates (see luad/conversions/functions.d#237). It is then GC.removeRooted in Lua's __gc metamethod which is the finalizer callback for Lua's own GC.

However, I'm not 100% sure how the conservative D GC handles manually added roots and ranges. Maybe it should be addRooting func.ptr (the context pointer of the delegate) instead?

Maybe some other issue is at play?

This is the fixed version:

class Game3D : RenderLayer
{
    private LuaTable playerTable;
    private Player player;

    ... // Player initialization, Asset loading etc

    private int getX() { return player.x; }
    ... // More functions

    public void setLua(LuaState lua)
    {
        playerTable = lua.newTable();

        playerTable["getX"] = &getX;

        auto plugins = dirEntries("plugins/", SpanMode.shallow, false);

        foreach(string file; plugins)
        {
            if(file.endsWith(".lua"))
            {
                try
                {
                    lua.doFile(file); // file containing my code
                }
                catch(LuaErrorException e)
                {
                    Logger.errln(e);
                }
                Logger.writeln("Loaded plugin from ", file);
            }
        }
    }
}

Indeed, (non-static) member functions have a different delegate context. I think maybe the fix would be to change GC.addRoot(udata); with GC.addRange(udata, T.sizeof); - I think currently it could be missing the context pointer, depending on whether the context pointer or the function pointer is first in a delegate.

edit:

And corresponding change in functionCleaner on line 222:

GC.removeRoot(lua_touserdata(L, 1));
->
GC.removeRange(lua_touserdata(L, 1));