Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lua Scripting in C#.

Similar presentations


Presentation on theme: "Lua Scripting in C#."— Presentation transcript:

1 Lua Scripting in C#

2 How to Set Things Up Download LuaInterface Unzip
Source code is available to recompile if needed 51Net4 available from 3103 site (ready for .NET 4) Unzip lua51.dll and LuaInterface.dll Place these DLL files in your project Add them as Reference Add “using LuaInterface;” atop code

3 Adding the DLL references

4 The LuaInterface Object
LuaInterface l = new Lua(); // executing a single command l.DoString("a=4"); //reading a variable Console.WriteLine(l["a"]); // finishing off l.Close();

5 Simple Lua Example

6 (internal runtime data)
What’s Happening C# Code Main l Heap (Memory) LuaInterface Instance (internal runtime data) a 4

7 LuaInterface (LI) is Persistent
Edit variables in script space Executing commands Writing to variables directly Note the value remains (i.e., think of them as properties within LI)

8 Running a Script In File
C# Code Main l Heap (Memory) Script File (on Disk) LuaInterface Instance (internal runtime data) a Lua Code a = 4 4 LuaInterface.Lua l = new Lua(); l.Close();

9 Errors… Must Change Property…

10 More Errors…

11 Solution: File Formatting

12 Lua and NET Interaction
Heap (Memory) C# Code Main Worker w LuaInterface Instance (internal runtime data) MainProgram a Worker LuaInterface l string Data DisplaySomething() { … } 4 Script File (on Disk) Lua Code a = 4 MainProgram.Data = “Hello World” MainProgram:DisplaySomething()

13 Accessing CLR/NET Objects
In Lua, we can access attributes using the dot (.) operator MainProgram.Data = "Hello World" We can also invoke methods using the colon (:) operator MainProgram:DisplaySomething()

14 Handling Events In C#, you can define new events
public delegate void SimpleEventHandler(); public event EventHandler SimpleEvent; Then you can raise the event SimpleEvent(this, null); Subscribing to the event enables handling SimpleEvent += new SimpleEventHandler(DoFunction);

15 Handling Events in Lua function handle_event() a = a + 1 MainProgram:DisplayState() end function handle_event_different() a = a + 10 MainProgram.SimpleEvent:Add(handle_event) MainProgram.SimpleEvent:Add(handle_event_different) a = 0

16 Testing the Event Handler
l = new Lua(); l["MainProgram"] = this; Timer t = new Timer(new TimerCallback(TimerFired), null, 0, 1000); Console.ReadLine(); l.Close(); private void TimerFired(Object state) { SimpleEvent(this, null); } function handle_event() a = a + 1 MainProgram:DisplayState() end function handle_event_different() a = a + 10 MainProgram.SimpleEvent:Add(handle_event) MainProgram.SimpleEvent:Add(handle_event_different) a = 0

17 Further Reading http://luaforge.net/projects/luainterface/


Download ppt "Lua Scripting in C#."

Similar presentations


Ads by Google