2

i'm using c# and LuaInterface and i need to send an event from my c# code to the working script. For example, it may be a button_click that interrupts working lua script or chanhes its logic. So, how can i do something like this?

  • you can't interrupt a Lua script; the script can use coroutine to temporarily yield control back to the application but it is still not "interrupting". – Oliver Mar 26 '14 at 13:11
  • There's no reason this question should be on hold. A callback is not an unusual concept. – Mud Mar 26 '14 at 14:36
  • Doesn't appear to be on hold at this moment. – Oliver Mar 26 '14 at 21:35

1 Answers1

2

You either require the Lua script to create a global function, which you call by name when the event occurs, or you register a function in C# which the Lua code calls to register a callback. The latter is a lot more flexible.

    private void Test()
    {
        lua.RegisterFunction("setEventHandler", this, GetType().GetMethod("SetEventHandler"));
        lua.DoString(@"
            setEventHandler( 
                function(arg) 
                    print('In my event handler:', arg) 
                end)
        ");
        CallEventHandler("This is an event!");
    }

    public delegate void EventHandler(String s);

    private EventHandler _eventHandler;

    public void SetEventHandler(EventHandler eventHandler)
    {
        _eventHandler = eventHandler;
    }

    public void CallEventHandler(string test )
    {
        _eventHandler(test);
    }
Mud
  • 28,277
  • 11
  • 59
  • 92